【问题标题】:if i type "Ctrl+Z",it will crash,how to fix it?如果我按“Ctrl+Z”,它会崩溃,如何解决?
【发布时间】:2015-05-03 19:12:28
【问题描述】:
    vector<string> svec;
    string str;
    while (cin >> str&&!cin.eof())
    {
        svec.push_back(str);
    }
    for (auto c:svec)
    {
        cout << c << " ";
    }

如果我输入tt tt tt,则输出为tt tt tt。 但是如果我什么都不输入,我输入 Ctrl+Z (windows + vs2013)会崩溃。 所以我尝试修复它。

 while (!cin.eof())
    {
        cin >> str;
        svec.push_back(str);
    }

现在,如果我什么都不输入,我输入 Ctrl+Z 不会崩溃。 但是如果我输入tt tt tt,输出是tt tt tt tt

现在我不知道如何解决它。请帮帮我。

【问题讨论】:

  • 您是否使用调试器查看崩溃的位置?也使用字符串流而不是std::cin 可能是一个好主意,在其中你用EOF 填充字符串流。另见stackoverflow.com/questions/5431941/…
  • &amp;&amp;!cin.eof() 是多余的。 operator&gt;&gt; 将返回流对象,当它到达 EOF 时,其计算结果为 false

标签: c++ inputstream eof


【解决方案1】:

你应该尝试一下:

while (cin >> str)
{
    svec.push_back(str);
}

为什么要额外的 tt
如果我展开你的 while 循环,它会变成:

1. buf [tt tt tt, not eof], vec []
  a. is eof no
  b. read and push str
2. buf [tt tt, not eof], vec [tt]
  a. is eof no
  b. read and push str
3. buf [tt, not eof], vec [tt tt]
  a. is eof no
  b. read and push str
4. buf [, not eof], vec [tt tt tt]
  a. is eof no
  b. read and push str [read fails, str contains old value and eof is set]
5. buf [eof], vec [tt tt tt tt]
  a. is eof yes
  b. break

您也可以阅读Why while(!feof(...) ) is almost always wrong

【讨论】:

  • 我在vs2013中试过你的代码,如果我什么都不输入然后输入ctrl + z,它仍然会崩溃,所以你能给我其他建议吗?
  • 你可以试试do { if(cin &gt;&gt; str) svec.push_back(str);} while (!cin.eof())。虽然我认为额外的检查是多余的,你应该尝试定位崩溃的根源。
  • 我试过了,也崩溃了。如果我在while 中使用!cin.eof()(不在do{}while 中),它不会崩溃。但是正如您的linksay,它进入循环的次数比作者预期的要多。如果出现读取错误,循环永远不会终止。。如果我不使用cin.eof(),它会崩溃。
  • 我检查了崩溃的位置并修复了它。非常感谢!
猜你喜欢
  • 2016-08-06
  • 2015-07-08
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 2011-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多