gpt4 book ai didi

c++ - while(cin) 出错

转载 作者:行者123 更新时间:2023-11-28 03:02:50 28 4
gpt4 key购买 nike

我只是在写另一个程序。并使用:

while (cin) 
words.push_back(s);

wordsstringvectorsstring

我的 RAM 使用量在 4 或 5 个输入后上升,SWAP 开始填充。我用的是 ubuntu?我只是不明白这么简单的代码怎么会引发如此糟糕的后果。或者,我的系统有问题吗?

编辑: 完整程序:

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

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main ()
{
vector<string> words;
string s;

cout << "Enter the string: ";
while (cin)
words.push_back(s);

for (vector<string>::const_iterator iter = words.begin();
iter != words.end(); ++iter)
cout << *iter;

return 0;
}

最佳答案

在您的代码中,您有while (cin),它将永远循环。这将导致您在 vector 中插入大量空字符串。你实际上从来没有尝试从标准输入中读取任何东西 - 你基本上以无限循环结束检查 cin 的状态(这在你终止流之前会很好),所以你最终尝试为空字符串分配大量空间。

你想写的是:

while (cin >> s)
words.push_back(s);

std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(words));

旁注:无论哪种情况,如果您打算在程序的其他位置再次使用 cin,您将需要清除其错误状态并刷新其缓冲区。

关于c++ - while(cin) 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334719/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com