【问题标题】:using cin to close a while loop使用 cin 关闭 while 循环
【发布时间】:2014-03-02 01:57:17
【问题描述】:

我正在尝试使用 while 循环来验证我的用户输入。请参阅下面的代码/while 循环。我希望他们输入一个浮点数,并且我正在尝试验证他们是否输入了一个数字而不是一个字母/句子。我认为这个循环应该可以工作,但是当我运行它时,如果我输入一个数字,它会在到达程序末尾之前出现,如果我输入一个字符串,它会触及cout 语句,无法请求cin,并且然后验证循环。如果您能解释发生了什么、为什么会发生以及如何解决它,我将不胜感激。

#include <iostream>   
using namespace std;

int main()
{
    float mph, i = 0;
    cout << "this program will calculate the distance a train will travel in a given amount of time." << endl;
    cout << "What is the speed of the vehicle in mph? ";
    cin >> mph;
    cout << endl;


    while (mph > -3.4E-38 && mph < 3.4E38);
    {
        cout << "that is not a number, do not pass go, do not collect $200 but DO try again." << endl;
        cin >> mph;
        // trace statement to check whats happening in the loop
        cout << "trace: " << mph << "faluer: " << i << endl;
        i++;
    }
    cout << "works twice" << endl;

    system("pause");
    return 0;
}

【问题讨论】:

  • Raphael,我想我有点理解你的意思(我是 C++ 新手)但也许我问错了问题。我想要做的是以最简单的方式验证用户输入。我要求用户提供数字,我想使用 while 语句来检查他是否输入了一个数字,不管它是整数还是浮点数,只要它不是字符串或字符。使用 while 语句执行此操作的最佳方法是什么?我认为我的 while 声明做到了,但也许这不是最好的方法?验证用户输入数字的最佳方法是什么?
  • 如果您指的是 Raphael 发布的答案,那么这正是它的作用,他还解释了它是如何工作的

标签: c++ while-loop


【解决方案1】:

您应该将 while 循环内的代码更改为:

cout<<"that is not a number, do not pass go, do not collect $200 but DO try again."<<endl;

if (!cin) { // we enter the if statement if cin is in a "bad" state.
    cin.clear(); // first we clear the error flag here
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // now we skip the input,
                                                                   // that led to the invalid state
}

cin>>mph;

如果您输入一个字符串并尝试将其读入带有cinfloatcin 将进入无效状态并拒绝读取任何输入直到被清除。
这就是我上面建议的代码试图解决的问题。请注意,您必须包含 &lt;limits&gt; 才能使其正常工作。

有关清除输入流的更多信息的相关链接:Why is this cin reading jammed?

【讨论】:

    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 2017-06-21
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    相关资源
    最近更新 更多