Hi, I'm having a little trouble with this program. I can't figure out why it's wrong.
Here is the original code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <cstring>
usingnamespace std;
int main() {
char the_string[81], *p;
cout << "Input a string to parse: ";
cin.getline(the_string, 81);
p = strtok(the_string, ", ");
while (p != NULL) {
cout << p << endl;
p = strtok(NULL, ", ");
}
system("PAUSE");
return 0;
}
This is copied exactly as it appears in the book. But it doesn't separate the tokens based on a comma and space", " like I pass to the strtok function, it uses just spaces instead. I have no idea why that is.
Then I was given an exercise to modify this program so that it prints how many tokens it finds. This was simple.
The next exercise however, wants me to rebuild the string from the tokens, and separate them with &'s. I have made an attempt which to me seems like it should work, but it causes the program to crash after it has displayed the tokens. Here's the code:
First is the tokens are seperated by spaces even though I explicitly told it to cut them at a comma and a space;", ".
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters. http://cplusplus.com/reference/clibrary/cstring/strtok/
You may use strstr instead.
The second is that when the program rebuilds the string and prints it garbage is displayed.