如何检查输入是否是没有任何其他字符的有效整数
How to check if the input is a valid integer without any other chars?
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int x;
cout << "5 + 4 = ";
while(!(cin >> x)){
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
如何检查用户输入的整数是否有效?在我上面写的这个程序中,如果用户输入9
,它应该是正确的,但是,如果用户输入9a
例如,它应该返回错误,但由于某种原因没有。我该如何纠正它?
我如何使用cin.peek((做到这一点
#include <iostream>
#include <limits>
#include <stdio.h>
using namespace std;
int main()
{
int x;
bool ok;
cout << "5 + 4 = ";
cin >> x;
while(!ok){
cin >> x;
if(!cin.fail() && (cin.peek() == EOF || cin.peek() == 'n')){
ok = true;
}
else{
cout << "Error, please try again." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
}
if (x == (5 + 4)){
cout << "Correct!" << endl;
}
else{
cout << "Wrong!" << endl;
}
return 0;
}
你可以读取一个字符串,从中提取一个整数,然后确保没有剩余的东西:
std::string line;
std::cin >> line;
std::istringstream s(line);
int x;
if (!(s >> x)) {
// Error, not a number
}
char c;
if (s >> c) {
// Error, there was something past the number
}
bool isIntegerNumber(const std::string& string){
std::string::const_iterator it = string.begin();
int minSize = 0;
if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
it++;
minSize++;
}
while (it != string.end() && std::isdigit(*it)) ++it;
return string.size()>minSize && it == string.end();
}
您有一个面向行的输入,因此您可能应该使用 getline
. 像这样:
bool
getIntFromLine( std::istream& source, int& results )
{
std::string line;
std::getline( source, line );
std::istringstream parse( source ? line : "" );
return parse >> results >> std::ws && parse.get() == EOF;
}
应该做这个伎俩。
使用它,您的循环将是:
while ( !getIntFromLine( std::istream, x ) ) {
std::cout << "Error, please try again." << std::endl;
}
请注意,此技术也意味着您不必担心关于清除错误或重新同步输入。
有关发生这种情况的原因,请查看此链接:
按顺序从流中提取字符并将其解析为 将它们解释为正确类型的值的表示形式, 存储为 val 的值。在内部,函数访问 通过首先构造哨兵对象(使用 noskipws 设置为 false(。然后(如果好的话(,它调用num_get::get(使用 流的选定区域设置(来执行提取和 解析操作,调整流的内部状态标志 因此。最后,它在返回之前摧毁了哨兵物体。
然后,如果您尝试执行以下操作,请观察该行为:
int x = 0;
cin >> x;
std::cout << x << std::endl;
std::cout << cin.good() << std::endl;
g++-4.8 -std=c++11 -O3 -Wall -pedantic -pthread main.cpp && echo "900a100" | ./a.out
// Output:
// 900
// 1
如果改为输入"a100",它将输出:
0
0
试试这个:
std::string input;
std::cin >> input;
if ( std::all_of(input.begin(), input.end(), std::isdigit) )
{
//input is integer
}
参考这个 :
C++ 修复了检查输入是否为整数的问题
我看到的适用于某些情况的一种是:
- 将输入读取为字符串。
cin >> str
- 解码为数字:atoi,或sscanf,或stringstream等。
- 将数字打印成字符串(使用 Sprintf 或字符串流(
- 检查它是否等于读取字符串。(使用字符串 ==,而不是字符*(
快速简单。 使用 Cin>>str 断字规则,接受负数,拒绝溢出的数字。但它确实拒绝"+10",在某些情况下你很满意,而在某些情况下你不满意。
如果你可以使用 C++11(并且你的编译器有完整的正则表达式支持(,你也可以使用 <regex>
库:
#include <iostream>
#include <limits>
#include <regex>
#include <string>
#include <utility>
int main()
{
std::string line;
std::pair<int, bool> value = std::make_pair(0, false);
std::cout << "5 + 4 = ";
while (!value.second)
{
while (!std::getline(std::cin, line))
{
std::cout << "Error, please try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
if (!std::regex_match(line, std::regex("(\+|-)?[[:digit:]]+")))
{
std::cout << "Error, please try again." << std::endl;
}
else
{
value = std::make_pair(std::stol(line), true);
}
}
if (value.first == (5 + 4))
{
std::cout << "Correct!" << std::endl;
}
else
{
std::cout << "Incorrect!" << std::endl;
}
return 0;
}
相关文章:
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么 c++ 中的 main() 函数不采用除 int 和 void 之外的任何其他返回类型
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 如何在不进行任何其他修改的情况下"pretty print" C++的XML字符串?
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 如何对 int 变量应用验证,使其仅接受整数数据,并且在任何其他数据的情况下不会出错?
- GLSL 计算着色器 使用查找表设置缓冲区会导致不写入任何数据,与其他数据设置相同的缓冲区有效
- 如何计算该程序的复杂性?是否有任何其他复杂性较低的解决方案
- C const在函数声明中以及其他任何地方的anmpersand的右侧
- 如何使用"std::multimap"或任何其他容器对多个值进行排序?
- 如何在任何其他全局变量或静态变量之前创建/构造类实例
- SSO在STD :: String以外的任何其他标准库容器中使用
- 程序在C++ Tutor中执行时有效,但在其他任何地方都不起作用
- 避免重复变量类型:Return type Resolver、C++11 auto、..其他任何东西
- 强制仅在某些代码中使用的特定构造函数,而不是其他任何地方
- 除了在类和程序之前,函数是否需要在其他任何地方声明?
- Ifstream不会读取整数或其他任何东西
- 3摄像机捕获与视频输入或其他任何东西
- 模板中的构造函数不同:一个用于字符串,另一个用于其他任何东西