I am new to C++, I’m working on tokenizing input. The commented line “cout<< “p: ” << p << endl;” makes the 2nd function call not execute, why?
#include <iostream>
#include <string>
#include <string.h> //for library strtok()
#include <sstream> //for useStringStream()
using namespace std;
void useStrTok(){
char myString[] = "The quick brown fox";
char *p = strtok(myString, " ");
while (p) {
cout<< "token: " << p<< endl;
p = strtok(NULL, " ");
//cout<< "p: " << p << endl;
}
}
void useStringStream(){
string myText("The quick brown fox");
istringstream iss(myText);
string token;
while(getline(iss,token, ' '))
{
cout << token << endl;
}
}
int main(){
useStrTok();
useStringStream();
return 0;
}
Because a null pointer maybe returned by strtok and print null pointer causes the crash. Check validation of pointer before accessing it:
See strtok reference