c++ - 为什么 strtok 不能与 stringstream 一起使用?

标签 c++ split stringstream strtok

考虑这些参数:

char words[8] = "one two";
string word1;
string word2;
stringstream ss;

这段代码的输出:

ss << strtok(words, " ");
ss >> word1;
ss << strtok(NULL, " ");
ss >> word2;
cout << "Words: " << word1 << " " << word2 << endl;

是:

Words: one

这段代码

ss << strtok(words, " ");
ss >> word1;
char* temp = strtok(NULL, " ");
word2 = temp;
cout << "Words: " << word1 << " " << word2 << endl;

输出是:

Words: one two

为什么stringstream可以处理strtok的第一个返回值,但不能处理第二个?

最佳答案

你应该插入语句

ss.clear();

清除流的eof状态。例如

    char words[8] = "one two";
    std::string word1;
    std::string word2;
    std::stringstream ss;
    ss << std::strtok(words, " ");
    ss >> word1;
    ss.clear();
    ss << std::strtok(NULL, " ");
    ss >> word2;
    std::cout << "Words: " << word1 << " " << word2 << std::endl;

关于c++ - 为什么 strtok 不能与 stringstream 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20814378/

相关文章:

c++ - 如何访问模板类型参数包中的类型索引?

python - 根据字符串拆分迭代并进行相同长度的拆分

r - 使用 dplyr 为每组应用 ggplot 函数并为每组设置标题

c++ - 从 std::stringstream 检索 char

c++ - 为什么循环 for stringstream 两次给我最后一个词

c++ - Visual Studio 错误 D8016 : '/ZI' and '/Gy' command-line options are incompatible

c++ - std::ignore 与结构化绑定(bind)?

c++ - auto 在 C++ 中做的事情是否与在 C 中完全不同?

python - 如何检查字符串是否为空或长度为零

c++ - 读取具有任意数量空格的输入字符串的一部分