Hi, I’m wondering if the contrasting output from the two code examples pasted below is normal behavior regarding strtok, and if so, if anyone could explain to a C++ novice why. Reading up on strtok informs me that the reason the source string is changed is that strtok puts in a string termination character whenever it finds a delimeter. But why in example 1 does it not change commandstring, while in example 2 it does?
The only difference between the two is that in the first code example I do
while in the second example I do
char *cmdstr;
...
cmdstr = commandstring.c_str();
My goal is simply to parse input commands as a control interface, so if there is a much better/easier way of parsing the input any suggestions are welcome.
Thanks,
Joe
Code1:
string commandstring = "5 4 3";
char delim[]=" ,.";
char *token;
cout << endl << "commandstring is now " << commandstring;
char cmdstr[] = commandstring.c_str();
cout << endl << "commandstring is then " << commandstring;
token = strtok(cmdstr,delim);
cout << endl << "token is " << token;
cout << endl << "commandstring is finally " << commandstring;
Output1:
commandstring is now 5 4 3
commandstring is then 5 4 3
token is 5
commandstring is finally 5 4 3
Code1:
[code]string commandstring = “5 4 3”;
char delim[]=" ,.";
char *token;
char *cmdstr;
cout << endl << "commandstring is now " << commandstring;
cmdstr = commandstring.c_str();
cout << endl << "commandstring is then " << commandstring;
token = strtok(cmdstr,delim);
cout << endl << "token is " << token;
cout << endl << "commandstring is finally " << commandstring;[/code]
Output2:
commandstring is now 5 4 3
commandstring is then 5 4 3
token is 5
commandstring is finally 5