سؤال

Consider these parameters:

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

The output of this code:

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

is:

Words: one

while for this code

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

the output is:

Words: one two

Why stringstream can handle the first returned value of strtok but not the second?

هل كانت مفيدة؟

المحلول

You should insert statement

ss.clear();

that to clear the eof state of the stream. For example

    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;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top