为什么strtok不适用于stringstream?

时间:2013-12-28 12:11:08

标签: 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的第一个返回值但不能处理第二个值?

1 个答案:

答案 0 :(得分:5)

您应该插入声明

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;