c++:检查输入是否是数字
C++ : check whether an input is a number
我想让用户输入一个键,我想检查键是否是一个数字,如果不是,抛出一个消息,如果是0,退出。
我读到一个答案,建议下面的方法在这里:isdigit() c++,可能简单的问题,但卡住
int key;
while (true){
cout << "Enter Key (Press 0 to Exit) : ";
if (cin>>key){
if (key == 0){ break; }
//Code goes here
}
else{cout<<"Key should be a digit "<<endl;}
}
但是我的代码进入一个无限循环,只要我输入一个字母,我不知道为什么。
任何帮助将不胜感激,如果有更好的替代方法,那么请建议。
cin>>key
尝试从控制台读取int
。
如果你输入了一个非数字字符,下一次从cin读取将把cin流设置为错误状态,并且在清除流的错误标志之前不能再从cin中读取任何内容。
cin.clear();
重置错误状态。
您还必须忽略输入的字符,这会导致
的失败模式。cin.ignore();
的例子:
int main()
{
int i;
while (1)
{
std::cin >> i;
if ( std::cin.fail())
{
std::cout << "Something went wrong with cin" << std::endl;
std::cin.clear();
std::cin.ignore();
}
else
{
std::cout << "input works, read: " << i << std::endl;
}
}
}
如果你想读一个单位数的控制台,也看这里:
从标准输入中捕获字符而不等待按回车
我的代码进入一个无限循环只要我输入一个字母
这是因为您将key
声明为int
,因此当std::cin
无法读取整数时,流被设置为错误状态,并且if
's中的break
语句不再可达。
一种可能的替代方法是从输入流中读取一行作为字符串,然后尝试将其转换为数字。
现在,给定OP的问题:
我想让用户输入一个密钥,我想检查密钥是否为
我不清楚(可能是我的错),如果键必须被认为是一个单位数或多位数。在下面的代码片段中,我将展示后一种情况。请注意,它也可能包括前者。
#include <iostream>
#include <string>
int main()
{
std::string line;
while ( std::getline(std::cin, line) )
{
if ( line.empty() ) continue;
try
{
int key = stoi(line);
if ( !key ) break;
// code that uses the key...
}
catch ( const std::invalid_argument &e )
{
std::cout << "Key should be a digit!n";
}
catch ( const std::out_of_range &e )
{
std::cout << "The value entered can't be represented by an int.n";
}
}
return 0;
}
相关文章:
- C ++:检查它是否是类中的数字
- 有没有办法检查用户输入是否是数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何以更有效的方式检查一个数字是否是素数?
- isdigit() 和 isalnum() 给出错误,因为输入是一个常量字符并且无法转换。其他可能查看输入是否为数字的方法?
- 试图使循环仅检查字符串是否仅数字,而在编程中允许的C IM中允许的负数是一个类项目
- 编写一个函数,用递归函数检查数字是否是正方形
- 如何判断变量是否是一个复杂的数字C
- 如何在不使用数学的情况下知道一个数字是否是回文
- 检查数字是否是素数,哪个是质数(C ++)
- C++检查从文件中读取的最后内容是否是数字
- 检查数字是否是素数
- 在将字符串转换为int之前,请检查字符串是否不是数字
- 我正在尝试做一个循环,检查输入是否是一个数字,如果没有再次询问
- 有没有一种方法可以测试一个输入是否是C++中的数字
- 有没有一种快速的方法来检查字符串是否是数字
- 逐个字符读取以查看它是否是数字
- c++检查输入是否是数字
- c++:检查输入是否是数字