C++ stringstream:无论字符串是否以空格结尾,都一致地提取?

C++ stringstream: Extracting consistently, regardless of whether the string ends with whitespace?

std::stringstream 中提取未知数量的项目的最简单方法是什么,无论字符串末尾是否有空格,其行为始终如一?

这是一个测试两种略有不同的方法的示例,以说明我的意思:

#include <cstdio>
#include <sstream>
#include <vector>
using namespace std;

void parse1(const char* text)
{
    stringstream text_stream(text);
    vector<string> string_vec;
    char temp[10];

    while (text_stream.good())
    {
        text_stream >> temp;
        printf("%s ", temp);
        string_vec.push_back(temp);
    }
    printf("\n");
}

void parse2(const char* text)
{
    stringstream text_stream(text);
    vector<string> string_vec;
    char temp[10];

    while (text_stream.good())
    {
        text_stream >> temp;
        if (text_stream.good()) 
        {
            printf("%s ", temp);
            string_vec.push_back(temp);
        }
    }
    printf("\n");
}

int main()
{
    char text1[10] = "1 2 3 ";
    char text2[10] = "1 2 3";

    printf("\nMethod 1:\n");
    parse1(text1);
    parse1(text2);

    printf("\nMethod 2:\n");
    parse2(text1);
    parse2(text2);
}

此代码产生以下输出。请注意,在以下两种情况之一中,他们每个人都搞砸了:

Method 1:
1 2 3 3
1 2 3

Method 2:
1 2 3
1 2

试试这个:

 void parse3(const std::string& text)
 {
   std::vector<std::string> string_vec;
   std::stringstream text_stream(text); 
   std::string temp;
   while ( text_stream >> temp)
   {
     std::cout<<temp<<" ";
     string_vec.push_back(temp);
   }
   std::cout<<std::endl; 
 } 

在您的循环条件中,您正在检查流中的错误,然后再尝试读取任何内容:

while(text_stream.good())
{
    text_stream >> temp;
    printf("%s ", temp);
    string_vec.push_back(temp);
}

应该按相反的顺序进行。惯用地,像这样:

// read to temp, then use operator bool() to get whether an error has occurred
while(text_stream >> temp)
{
    printf("%s ", temp);
    string_vec.push_back(temp);
}

第二个版本就不用说了,都是基于同样的错误