如何检查输入数字整数是否不浮点? [英] How to check if the input number integer not float?

查看:108
本文介绍了如何检查输入数字整数是否不浮点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查输入是否有效,但是当我运行此代码时,我看到它仅检查输入的字符.如果我输入一个浮点数,它将使用它,并且将使用不带小数部分的整数.

I want to check if the input is valid, but when i do run this code I see that it checks only input for charcters. If i input a float number it will take it and going to use like integer without fractional part.

#inclide <iostream>
using namespace std;
...
int n;
cout << "Your input is: "<<endl;
cin >> n;
while (cin.fail()) {
    cout << "Error. Number of elements must be integer. Try again: " << endl;
    cin.clear();
    cin.ignore(256, '\n');  
    cin >> n;
}
...        
      `

那么,如何使此代码查看输入是否为浮点型?

So, how to make this code see if the input is float?

推荐答案

基于 Raindrop7 的解决方案,这是完整的代码来满足您的需求:

Building on Raindrop7's solution, here's the full code to do what you need:

#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double m;
    cout << "Your input is: "<<endl;
    cin >> m;
    while (cin.fail() || (m-floor(m)))
    {
        cout << "Error. Nubmer of elements has to be integer. Try again: " << endl;
        cin.clear();
        cin.ignore(256, '\n');  
        cin >> m;
    }
    int n = (int)m;
    return 0;
}

以下是示例输出:

Your input is: 
2.7
Error. Nubmer of elements has to be integer. Try again: 
erer
Error. Nubmer of elements has to be integer. Try again: 
2

这篇关于如何检查输入数字整数是否不浮点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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