【问题标题】:Split a string into a vector of words [duplicate]将字符串拆分为单词向量[重复]
【发布时间】:2014-10-21 18:45:18
【问题描述】:

我有一个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,正确的代码是什么?

【问题讨论】:

  • @CaptainObvlious:不是真的,不。
  • 基本逻辑:ss.good()无法预测未来!
  • @LightnessRacesinOrbit - 非常正确。关闭投票被撤回。

标签: c++ string stream


【解决方案1】:

ss.good() 只告诉您到目前为止情况是否良好。它并没有告诉你你接下来读的东西会很好。

使用

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

现在您首先阅读tmpstr,然后检查流的状态。相当于这样:

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

【讨论】:

  • 感谢您的回答。我发现返回值是istream类型的,所以我写了while (istream obj = ss &gt;&gt; tmpstr) ,但是好像错了。那么ss &gt;&gt; tmpstr 背后的语法是什么?
  • 感谢您的解释!我学到了很多。
猜你喜欢
  • 2011-06-12
  • 2014-06-09
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多