Concerning string.cstr()

M

Michael Lawson

I may be a bit ignorant, or I haven't searched hard enough,
but how exactly is one to grab the finger character of a
string variable? The only way I know how to at the moment
looks a bit ugly, ie: string.cstr()[0]; Is there another
way I can do this? I figure if it *looks* ugly, then there
probably is a better way. And as a result, I've a tendency
to use C-style strings in C++ because I can't find a better
way of doing this, or scanning each individual letter of a
string in some occasions.

Thanks much,
Michael
 
G

Gianni Mariani

Michael said:
I may be a bit ignorant, or I haven't searched hard enough,
but how exactly is one to grab the finger character of a
string variable? The only way I know how to at the moment
looks a bit ugly, ie: string.cstr()[0]; Is there another
way I can do this? I figure if it *looks* ugly, then there
probably is a better way. And as a result, I've a tendency
to use C-style strings in C++ because I can't find a better
way of doing this, or scanning each individual letter of a
string in some occasions.




#include <iostream>

int main()
{

std::string str = "ABCD\n";

str[0] = 'X';

std::cout << str;
}
 
P

Pierre

I may be a bit ignorant, or I haven't searched hard enough,
but how exactly is one to grab the finger character of a
string variable? The only way I know how to at the moment
looks a bit ugly, ie: string.cstr()[0];

you can use the at(position) function

for(std::string::size_type i=0;i<s.size();++i)
{
cout << s.at(i);
}

or you can use the [] operator

for(std::string::size_type i=0;i<s.size();++i)
{
cout << s;
}

or you can use the std::string::iterator

for(std::string::iterator i=s.begin();i!=s.end();++i)
{
cout << (*i);
}

Is there another
way I can do this? I figure if it *looks* ugly, then there
probably is a better way.

you should have a look at a C++ documentation about the standard
template library (STL).
And as a result, I've a tendency
to use C-style strings in C++ because I can't find a better
way of doing this, or scanning each individual letter of a
string in some occasions.

I did the same when I was learning C++. The more you learn STL and
understand how it works, the less you will use some features of C
(stdio, callback, malloc/realloc... etc...)

Pierre
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top