while循环中的迭代在不接受输入的情况下运行和结束

Iteration in while loop runs and ends without taking inputs?

本文关键字:运行 情况下 结束 输入 循环 迭代 while 不接受      更新时间:2023-10-16

我想根据当前输入拆分字符串并将其存储在result deque中,然后再次执行此操作while (count-- > 0)

count = 3

输入字符串:abc defghi

   while (count-- > 0){
    cout << " start of while loop" << endl;
    deque<string> result;
    string str2;
    cin >> str2;
    istringstream iss(str2);
    for(string s; iss >> s; ){
      result.push_back(s);
    } 
    cout << "result.size() " << result.size() << endl;
    }
   }

问题:结果大小保持为1,while循环自动运行3次

Todo:结果大小应为3

输出:

start of while loop
abc def ghi
result.size() 1
start of while loop
result.size() 1
start of while loop     
result.size() 1

我应该能够接受3次输入,但是while循环自动运行3次而不接受输入和结束。为什么会这样?

而不是:

  while (count-- > 0){
    cout << " start of while loop" << endl;
    deque<string> result;  // result created inside loop

你想要这个

  deque<string> result; // result created outside loop
  while (count-- > 0){
    cout << " start of while loop" << endl;

否则,每次循环迭代都会重新创建result。

另外,听起来您希望abc def被视为单个输入,但是cin >> str2读取一个单词,而不是一行。要读取一行,使用getline代替:

getline(cin,str2);
相关文章: