|
-
October 9th, 2005, 05:47 PM
#1
How to convert string variable to char array
Code:
string myStrArray[10];
for(int i = 0; i < 10; ++i)
{
myStrArray[i] = "a";
}
string myString;
cin>>myString; // input myString = "a"
char charStr1[] = myStrArray[0];
char charStr2[] = myString;
if(strcmp(charStr1, charStr2) == 0)
cout<<"Same!!!";
When I try the code above, it was an error. I have already changed the string variable to char array, but somehow it still does not work.
Any help would much be appriciated.
hl
-
October 9th, 2005, 06:02 PM
#2
Re: How to convert string variable to char array
http://www.msoe.edu/eecs/cese/resources/stl/string.htm
Check out the string::c_str() member. But why strcmp() when the == operator is overloaded to compare string objects?
-
October 9th, 2005, 06:11 PM
#3
Re: How to convert string variable to char array
When calling functions that require a const char*, the c_str() method is the way to go. Usually there is an equivalent for C++ strings (as Calculator mentioned), so you don't have to do that at all. In this case the string class has operator== overloaded and a compare() method as well.
If you need a non-const character array, you'll need to use strcpy to copy the string's contents into a new character array that you've allocated memory for. Since strcpy takes a const char* for the source, you would of course need to use the c_str() method there.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|