C++ 检查 cin 输入流产生一个整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18728754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking cin input stream produces an integer
提问by user2766546
I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
我正在输入这个,它要求用户输入两个整数,然后它们将成为变量。从那里它将执行简单的操作。
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
如何让计算机检查输入的内容是否为整数?如果没有,要求用户输入一个整数。例如:如果有人输入“a”而不是 2,那么它会告诉他们重新输入一个数字。
Thanks
谢谢
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
回答by Chemistpp
You can check like this:
你可以这样检查:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
此外,您可以继续获取输入,直到通过以下方式获得 int:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
编辑:为了解决下面关于像 10abc 这样的输入的评论,可以修改循环以接受字符串作为输入。然后检查字符串中是否有任何不是数字的字符,并相应地处理这种情况。在这种情况下,不需要清除/忽略输入流。验证字符串只是数字,将字符串转换回整数。我的意思是,这只是袖手旁观。可能有更好的方法。如果您接受浮点数/双精度数(必须在搜索字符串中添加“.”),这将不起作用。
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
回答by Dúthomhas
Heh, this is an old question that could use a better answer.
呵呵,这是一个老问题,可以使用更好的答案。
User input should be obtained as a stringand then attempt-convertedto the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
用户输入应作为字符串获取,然后尝试转换为您想要的数据类型。方便的是,这还允许您回答诸如“我的输入是什么类型的数据?”之类的问题。
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
这是我经常使用的一个函数。存在其他选项,例如在 Boost 中,但基本前提是相同的:尝试执行字符串→类型转换并观察成功或失败:
template <typename T>
std::optional <T> string_to( const std::string& s )
{
std::istringstream ss( s );
T result;
ss >> result >> std::ws; // attempt the conversion
if (ss.eof()) return result; // success
return {}; // failure
}
Using the optional
type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
使用optional
类型只是一种方式。您还可以在失败时抛出异常或返回默认值。什么都适合你的情况。
Here is an example of using it:
下面是一个使用它的例子:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
限制和类型识别
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
当然,为了使其工作,必须存在一种方法来明确地从流中提取您的数据类型。这是 C++ 中事物的自然顺序——即一切照旧。所以这里没有惊喜。
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int
and double
, check for int
first, since anything that converts to an int
is also a double
.
下一个警告是某些类型包含其他类型。例如,如果您试图区分int
and double
,请int
首先检查,因为转换为 an 的任何内容int
也是 a double
。
回答by nook
There is a function in c called isdigit()
. That will suit you just fine. Example:
c 中有一个函数叫做isdigit()
. 那会很适合你。例子:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
从这里
回答by Zac Howland
If istream fails to insert, it will set the fail bit.
如果 istream 插入失败,它将设置失败位。
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int
in this case) propertly inserted.
您可以在 do-while 循环中进行设置,以正确int
插入正确的类型(在本例中)。
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
更多信息:http: //augustcouncil.com/~tgibson/tutorial/iotips.html#directly
回答by Zac Howland
You can use the variables name itself to check if a value is an integer. for example:
您可以使用变量名称本身来检查值是否为整数。例如:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
回答by Eduardo Floriani
You could use :
你可以使用:
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.
我很确定它有效。