is there any way to convert c style strings to c++ strings? I know you can go the other way, I was just curious as to whether or not you could go this way.
is there any way to convert c style strings to c++ strings? I know you can go the other way, I was just curious as to whether or not you could go this way.
Code:string text_string; char text[]="hello"; for(int i=0; i<strlen(text); i++) text_string += text[i]; cout<<text_string<<endl;
I'm surprised it doesn't have a member function that can do this, or even a constructor that allows this.
....
I just looked it up. There exists a constructor like so:
string( const char *str );
You can use this.
Last edited by JasonD; 04-13-2003 at 08:03 PM.
"I just looked it up."
I suspected there was, but it took me less time to write the code than it would have taken to look it up. All the string functions are very easy to define yourself.
[edit]Code:char text[]="hello"; string text_string(text); cout<<text_string<<endl;
Last edited by 7stud; 04-13-2003 at 08:06 PM.
couldn't be easier:
Code:#include <iostream> #include <string> using namespace std; int main() { char cStr[] = "muddy waters"; string cPlusStr(cStr); cout << cPlusStr << endl; return 0; }
Thanks for the replies, but oddly enough, the hardest solution fit my purposes the best.
Greetings,Originally posted by fbplayr78
Thanks for the replies, but oddly enough, the hardest solution fit my purposes the best.
std::string also has the '=' operator defined that you can use like:
I fail to see how iterating through a C string and appending every char to an std::string works better than just using the constructor or the '=' operator, because the result will be exactly the same! Except for the overhead of calling the '+=' operator in every iteration. Unless you are parsing the C string for 'valid' chars, I say use the other methods.Code:#include <iostream> #include <string> int main { std::string str1("Hello"); // The constructor std::string str2 = "Hello"; // This is the same as the above because in both cases the compiler // will invoke the constructor not the '=' operator as one might think, // this because this string object is still being created. std::string str3; // An empty string str3 = "world!"; // The '=' operator std::cout << str1 << str3 << std::endl; }