检查用户是否输入一个float到int var? [英] check if user input a float to a int var?
本文介绍了检查用户是否输入一个float到int var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个int var;并且使用cin,但是如何检查用户是否输入浮点数或者给我这个问题的解决方案?
I have a int var; and using cin, but how to check if user input a float or give me a solution for this problem?
推荐答案
简单的方法做到这一点。通过>>输入。 operator
实际上不是用于与可能进入错误的事物的人的交互。您必须将输入读为字符串,然后使用诸如strtol的函数或自己的手动代码来检查它。
There is no easy way of doing this. Input via the >> operator
is really not intended for interaction with humans who may enter the wrong thing. You will have to read the input as a string and then check it using a function like strtol, or your own hand-rolled code.
以下是使用strtol的方法:
Here's an outline of an approach using strtol:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool GetInt( istream & is, int & n ) {
string line;
if ( ! getline( is, line ) ) {
return false;
}
char * ep;
n = strtol( line.c_str(), & ep, 10 );
return * ep == 0;
}
int main() {
int n;
while(1) {
cout << "enter an int: ";
if ( GetInt( cin, n ) ) {
cout << "integer" << endl;
}
else {
cout << "not an integer" << endl;
}
}
}
这篇关于检查用户是否输入一个float到int var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文