如何检查输入是否是没有任何其他字符的有效整数? [英] How to check if the input is a valid integer without any other chars?

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

问题描述

  #include< iostream> 
#include< limits>

using namespace std;

int main()
{
int x;
cout<< 5 + 4 =;
while(!(cin>> x)){
cout< 错误,请重试。 << endl;
cin.clear();
cin.ignore(numeric_limits< streamsize> :: max(),'\\\
');
}
if(x ==(5 + 4)){
cout< 正确! << endl;
}
else {
cout<< 错误! << endl;
}
return 0;
}

如何检查用户是否输入了有效的整数?在上面写的程序中,如果用户输入 9 ,那么应该是正确的,但是如果用户输入 9a 例如,它应该返回一个错误,但它不是由于某种原因。

 


$ b code> #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()=='\\\
')){
ok = true;
}
else {
cout<< 错误,请重试。 << endl;
cin.clear();
cin.ignore(numeric_limits< streamsize> :: max(),'\\\
');
}
}

if(x ==(5 + 4)){
cout< 正确! << endl;
}
else {
cout<< 错误! << endl;
}

return 0;
}


解决方案

从它提取一个整数,然后确保没有什么留下:

  std :: string line; 
std :: cin>>线;
std :: istringstream s(line);
int x;
if(!(s> x)){
//错误,不是数字
}
char c;
if(s>> c){
//错误,有过去的数字
}


#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;
}

How can I check if the user inputs a valid integer? In this program I wrote above, if the user inputs 9, it should be correct, however, if the user inputs 9a for example, it should return an error, but it doesn't for some reason. How can I correct it?

How I did it using 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;
}

解决方案

You could read a string, extract an integer from it and then make sure there's nothing left:

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
}

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

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