我正在尝试编写一个程序来解析一个字符串并给出每个单词的位置。我无法弄清楚为什么我会得到一个
“DEBUG ASSERTION FAILED”Experssion:无效的空指针
窗口到达字符串的最后一个单词。
char * pointer_char;
int pos = 0;
std::string str = "This test string will fail at this word..!. ";
int i = 0;
int length = str.length();
char * c = new char [str.size()+1];
std::copy(str.begin(), str.end(), c);
c[str.size()] = '\0';
cout << "Testing string is " << str << endl << endl;
pointer_char = strtok (c," ");
while(pointer_char != NULL)
{
cout << pointer_char << endl;
pointer_char = strtok(NULL, " .!");
string word = pointer_char;
size_t found= str.find(word);
if (found!=string::npos)
cout << "Position of " << word << " found at: " << int(found) << endl;
system("pause");
}
return 0;
答案 0 :(得分:1)
问题是你没有检查strtok的返回值。
pointer_char = strtok(NULL, " .!");
string word = pointer_char;
你只是在循环的顶部进行测试。
pointer_char = strtok(nullptr, " .!");
if (pointer_char == nullptr)
break;