This question already has answers here:
Testing stream.good() or !stream.eof() reads last line twice [duplicate]
                                
                                    (3个答案)
                                
                        
                        
                            How do I iterate over the words of a string?
                                
                                    (76个答案)
                                
                        
                                5年前关闭。
            
                    
我有一个string"ABC DEF ",最后是空格。我想将其转换为像vector这样的字符串的{"ABC" "DEF"},所以我使用了stringstream

string s = "ABC DEF ";
stringstream ss(s);
string tmpstr;
vector<string> vpos;
while (ss.good())
{
    ss >> tmpstr;
    vpos.push_back(tmpstr);
}


但是,结果vpos{"ABC" "DEF" "DEF"}。为什么最后一个单词将在向量中重复?如果需要使用stringstream,正确的代码是什么?

最佳答案

ss.good()仅告诉您到目前为止情况是否良好。它并没有告诉您阅读的下一本书会很好。

使用

while (ss >> tmpstr) vpos.push_back(tmpstr);


现在,您首先阅读tmpstr,然后检查流的状态。等效于:

for (;;) {
    istream &result = ss >> tmpstr;
    if (!result) break;
    vpos.push_back(tmpstr);
}

关于c++ - 将字符串分割成单词 vector ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25539747/

10-13 23:13