Click to See Complete Forum and Search --> : How to convert string variable to char array


hlchuah77
October 9th, 2005, 05:47 PM
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.

Calculator
October 9th, 2005, 06:02 PM
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? ;)

jlou
October 9th, 2005, 06:11 PM
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.