【问题标题】:cin buffer Issues in C++C++ 中的 cin 缓冲区问题
【发布时间】:2020-07-25 15:15:45
【问题描述】:

我正在学习 C++,所以我不完全理解我的代码在这里发生了什么,但从我能够收集到的信息来看,它似乎可能是某种缓冲区问题。

#include <stdio.h>
#include <vector>
#include <iostream>
#include <typeinfo>

using namespace std;

bool stopRun = true;
int height, average, total, count;
vector <int> heights;

int main ()
{
    while (stopRun)
    {
        cout << "Enter a height, or 'end' to quit: ";
        cin >> height;
        if (typeid(height).name() == "i")
        {
            heights.push_back(height);
            cout << heights[0];
            count++;
        }
        else if (typeid(height).name() == "i")
        {
            cout << "\nPlease enter an integer: ";
            continue;
        }
        if (count == 5)
        {
            stopRun = false;
        }
    }
    for (int i = 0; i < heights.size(); i++)
    {
        total += heights[i];
        cout << "\nTotal: " << total;
    }
    return 0;
}

由于某种原因,这段代码会不断输出:“输入一个高度,或者'end'退出:”。在早期版本中,它会输出:“输入高度,或者‘结束’退出:请输入一个整数:”。

我认为发生的事情是我的“cin >> height;”行从“请输入一个整数:”中提取输出并将其视为我的输入,这将其标识为不是整数类型,从而启动无限循环。

如何清除输入缓冲区以使其不引入 cout 语句?或者这甚至是我在这里遇到的问题?

提前致谢!

【问题讨论】:

  • cin &gt;&gt; height; 如果输入的不是整数,cin 将处于错误状态。您需要清除错误并使用错误的输入。 Why would we call cin.clear() and cin.ignore() after reading input?
  • 另一种选择是将输入读取为std::string 并使用std::stoi() 转换为int
  • typeid 的用途是什么?他们没有告诉您cin 是否成功读取整数。另外,ifelse if 分支中的条件不一样吗?

标签: c++ buffer infinite-loop cin cout


【解决方案1】:
if (string(typeid(height).name()) == "i")

你错的是指针和字符串的比较。由于 typeid(height).name() 返回一个指向带有对象名称的 c 字符串的指针。

【讨论】:

    【解决方案2】:

    您正试图在同一行代码中读取intstring。我建议您使用getline() 读取输入并尝试将string 转换为int

    std::string input;
    while (heights.size() != 5) {
        cout << "Enter a height, or 'end' to quit: ";
        if (std::getline(cin, input)) {
            if (input == "end") break;
            try {
                heights.push_back(std::stoi(input));
            }
            catch (std::invalid_argument e) {
                cout << "\nPlease enter an integer: ";
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以在你的程序 fflush(stdin) 开始时使用这个函数。它将清除您的输入缓冲区。

      【讨论】:

        【解决方案4】:

        我建议抓住字符串。如果字符串不是“结束”,则在 try/catch 中转换为数字

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-25
          • 1970-01-01
          • 1970-01-01
          • 2018-12-15
          • 1970-01-01
          • 1970-01-01
          • 2018-04-24
          • 2012-09-12
          相关资源
          最近更新 更多