【问题标题】:do...while() repeating the last string twicedo...while() 将最后一个字符串重复两次
【发布时间】:2016-05-26 18:22:16
【问题描述】:

以下代码将提供的字符串/行拆分为字符。为什么循环重复最后一个字符串两次?如何解决?

#include <iostream>
#include <vector>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string main, sub;
    cout << "Enter string: ";
    getline(cin, main);
    istringstream iss(main);
    do
    {
        iss >> sub;
        cout << sub << endl;
        vector<char> v(sub.begin(), sub.end());
        for(int i = 0; i < v.size(); i++)
         {
             cout << v[i] << endl;
         }
    } while (iss);
    return 0;
}

输入:

你好世界

期望的输出

你好
h
电子
l
l
o
世界
w
o
r
l

实际输出:

你好
h
电子
l
l
o
世界
w
o
r
l
d
世界
w
o
r
l

我已经尽可能删除了与问题无关的元素

【问题讨论】:

标签: c++ do-while istringstream


【解决方案1】:

在最后一次运行中,iss 引发了一个失败,因此 sub 的值没有更新,从而导致重复发生。看到这一点的一种方法是在 do 循环的开头将 sub 设置为空字符串。为避免此类问题,我会执行以下操作

while(iss>>sub){
  cout<<sub<<endl;
  etc
}

另外,我想指出你可以遍历一个字符串,因为它可以被视为一个 char*,所以你不需要向量转换的东西。

【讨论】:

    【解决方案2】:

    问题是 istream 的 conversion to bool 仅在设置了 failbit 或 badbit 时返回 false,但在流为空时不返回。例如,在您尝试从空 istream 中提取字符串后设置失败位。这就是为什么您的循环多运行一次的原因:当 istream 为空时,未设置故障位,只有在额外迭代中无法提取任何字符串后,才设置故障位并终止循环。一个解决方案可能是使用:

    #include <iostream>
    #include <vector>
    #include <sstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        string main, sub;
        cout << "Enter string: ";
        getline(cin, main);
        istringstream iss(main);
        while(iss >> sub)
        {
            cout << sub << endl;
            vector<char> v(sub.begin(), sub.end());
            for(int i = 0; i < v.size(); i++)
             {
                 cout << v[i] << endl;
             }
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2014-03-04
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多