【问题标题】:Why does strtok not work with stringstream?为什么 strtok 不能与 stringstream 一起使用?
【发布时间】:2013-12-28 12:11:07
【问题描述】:

考虑这些参数:

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 的 ostream 部分命中 EOF 并设置 eof 标志。除非您手动清除该标志,否则无法进一步输入。
  • 它可以处理所有这些,但是您没有正确使用它。您正在尝试将stringstream 用作容器,但它是一个数据流

标签: c++ split stringstream strtok


【解决方案1】:

你应该插入语句

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 2014-01-10
    • 2018-03-09
    • 2021-06-14
    • 2012-10-09
    • 2020-03-18
    • 2017-11-21
    • 2019-04-11
    相关资源
    最近更新 更多