【问题标题】:C++ Check if input is float using only #iostreamC ++仅使用#iostream检查输入是否为浮点数
【发布时间】:2013-10-31 22:42:54
【问题描述】:

我想验证用户输入是否为浮点数,程序检查输入是否为浮点数并打印“数字正常”,否则打印“数字不正常”并继续循环而不采取失败尝试考虑循环,以其他方式让他再次尝试输入浮点数。

问题是一旦用户输入“字符”,程序就会进入无限循环。我真正想要它做的只是打印“数字不好”然后继续。

谁能告诉我为什么会这样,也请考虑不要使用任何额外的库。

#include <iostream>
#include <windows.h>


using namespace std;
int main()
{
    int x;
    float num;
    cout << "Please enter the amount of numbers you wish to enter" << endl;
    cin >>  x;

    cout << "Please enter the numbers" << endl;
    for(int i=0; i < x;) {
        if(!(cin >> num)) {
            cout << "Number isn't fine" << endl;
            continue;
        }
        cout << "Number is fine" << endl;
        ++i;
    }
    system("pause");
}

@Steve 您的解决方案同时使用 cin.clear() 和 cin.ignore

@AndyG 感谢您的帮助,但不幸的是我仅限于最简单的方法。

如果有人想知道它在未来的样子,这里是最终代码。

#include <iostream>
#include <windows.h>

using namespace std;
int main()
{
    int x;
    float num;
    cout << "Please enter the size of numbers" << endl;
    cin >>  x;

    cout << "Please enter the numbers" << endl;
    for(int i=0; i < x;) {
        if(!(cin >> num)) {
            cin.clear();
            cin.ignore();
            cout << "not a float number" << endl;
            continue;
        }
        cout << "Number is fine" << endl;
        ++i;
    }
    system("pause");
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    如果cin &gt;&gt; num 未能读取数字,则流将进入失败状态(即设置了failbit),并且不会读取导致其失败的字符。你永远不会对 clear() 失败状态或 ignore() 错误数据做任何事情,所以你永远循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2013-11-29
      • 2010-11-22
      • 2020-05-05
      相关资源
      最近更新 更多