【问题标题】:Clear entire line from cin instead of one character at a time when the user enters bad input当用户输入错误时,一次从 cin 清除整行而不是一个字符
【发布时间】:2015-01-19 18:33:52
【问题描述】:

我对 cin 的一些命令有疑问。我对 c++ 还是很陌生,所以请耐心等待。

我正在做一个简单的计算程序,用户输入一个值,程序使用输入进行计算。我正在尝试创建一个循环来检查输入以确保用户输入和编号。经过一番研究,我发现使用cin.clearcin.ignore 会清除以前的输入,以便用户可以在循环检查后输入一个新值以查看它是否不是数字。它运行良好,除非用户输入大于 1 个字母的单词。然后它循环并一次删除每个字母,直到前一个 cin 被清除。有没有办法一次删除整个单词而不是一个字符?我觉得我错误地解释了 cin 命令的实际作用。

这里是有问题的代码:

//Ask the user to input the base
cout << "Please enter the Base of the triangle" << endl;
cin >> base;

//A loop to ensure the user is entering a numarical value
while(!cin){

    //Clear the previous cin input to prevent a looping error
    cin.clear();
    cin.ignore();
    //Display command if input isn't a number 
        cout << "Not a number. Please enter the Base of the triangle" << endl;
        cin >> base;
}

【问题讨论】:

标签: c++ loops cin


【解决方案1】:

我认为您可以在网上通过多种方式获得答案。这仍然对我有用:

#include <iostream>
#include <limits>

using namespace std;

int main() {
    double a;
    while (!(cin >> a)) {
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        cout << "Wrong input, retry!" << endl;
    }
    cout << a;
}

此示例比 cmets 中链接的示例更简单,因为您希望用户输入,每行一个输入。

【讨论】:

  • 这确实和我之前提到的代码一样。但是,当我运行它时,它仍然给出类似的结果。如果我输入一个长度为 4 个字母的单词,则循环运行 4 次,输出错误消息“不是数字”4 次,然后用户才能输入另一个值。我想这就是我真正想要避免的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2022-12-18
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多