C ++使用#iostream检查输入是否为float [英] C++ Check if input is float using only #iostream

查看:222
本文介绍了C ++使用#iostream检查输入是否为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证用户输入是否为Float,程序检查输入是否为float并打印Number is fine,否则打印Number is not fine,并继续循环,而不采用失败尝试考虑循环,换句话说,它再次尝试输入一个浮点数。

I would like to validate if the user input is Float or not, the program checks if the input was float and prints "Number is fine" else it prints "Number is not fine" and it continue the loop without taking the failed attempt in consideration of the loop, in other way it gives him another try to enter a float number instead.

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

The problem is that the program goes on infinity loop once the user enter a "Character". what i actually want it to do is just printing "Number isn't fine" then continue.

任何人都可以告诉我为什么会发生,也请不要使用任何其他库。

Can anybody tell me why does this happen, also please consider not to use any additional libraries.

#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。忽略

@Steve your solution worked by using both cin.clear() and cin.ignore

@AndyG感谢您的帮助,但不幸的是我只能用最简单的方法。

@AndyG Thanks for your help but unfortunately im limited to the simplest way.

代码,如果有人想知道它在未来的样子。

Here is the final code if somebody wanted to know how it looks in the future.

#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");
}


推荐答案

> cin>> num 无法读取一个数字,然后流被置于失败状态(即,设置 failbit ),读过去导致它失败的字符。您从不对 clear()失败状态或 ignore()执行任何操作,因此您永远循环。

If cin >> num fails to read a number then the stream is put into the failed state (that is, the failbit is set), and it doesn't read past the character that caused it to fail. You never do anything to clear() the fail state or to ignore() the bad data, so you loop forever.

这篇关于C ++使用#iostream检查输入是否为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆