我正在尝试使用函数strtok来标记用户的输入,然后在每个单词之间打印出带有新行的结果。但是,会弹出此错误。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
string str;
char *tokenPtr;
cout << "Enter a sentence : " << endl;
getline(cin, str);
tokenPtr = strtok( str, " " ); // ERROR: No matching function for call to 'strtok'
while( tokenPtr != NULL ) {
cout << tokenPtr << endl;
tokenPtr = strtok( NULL, " " );
}
return 0;
}
标准 C 函数strtok
用于包含字符串的字符数组。
因此,当您提供类型为std::string
的参数时,它的第一个参数具有char *
的类型。
你可以改用标准的字符串流std::istringstream
,例如
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s;
std::cout << "Enter a sentence : ";
std::getline( std::cin, s, 'n' );
std::string word;
for ( std::istringstream is( s ); is >> word; )
{
std::cout << word << 'n';
}
return 0;
}
程序输出可能如下所示
Enter a sentence : Hello Naoki Atkins
Hello
Naoki
Atkins