Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 431
user2699298 Avatar asked Nov 29 '13 13:11

user2699298


People also ask

How do you validate if an input is an integer?

To check if the input string is an integer number, convert the user input to the integer type using the int() constructor. To check if the input is a float number, convert the user input to the float type using the float() constructor.

How do you check if an input is a number?

Use the str. isdigit() method to check if a user input is a number, e.g. if num. isdigit(): . The isdigit() method will return True for all positive integer values and False for all non-numbers, floating-point numbers or negative numbers.

How do you check if a input is an integer in Python?

Use the str. isdigit() method to check if a user input is an integer. The isdigit() method will return True for all positive integer values and False for all non-numbers, floating-point numbers or negative numbers.


1 Answers

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
}
like image 122
Angew is no longer proud of SO Avatar answered Nov 15 '22 06:11

Angew is no longer proud of SO