how to check if number is integer?

Hi, how do you check if a number inputted by cin object is a integer? If it's a double then i want it to spit out an error and ask me to input another number.

thanks
Since integers do not have decimals or "/", you can check for the decimal or "/" character.
closed account (3bfGNwbp)
Since integers do not have decimals or "/", you can check for the decimal or "/" character.

I assume you mean the null character('\0') found in strings. Am I correct?
I'm not very good a terminology yet, I'm still learning. I was actually thinking you could use a function like substr() or something and check for either of those characters... maybe it was a bad suggestion >.<
Hi, I'm also a newbie but I think this should work:

1
2
3
4
5
6
int test;
while (!(cin >> test))
{
cout << "Wrong input. Please, try again: ";
cin.clear();
}


If there's a double (. character) or a string in the input queue the cin object should be false (0), so if you put !, it keeps asking you for the right input.
closed account (j2NvC542)
1
2
3
4
5
6
int i;

do {
    cout << "Please enter an integer: ";
    cin >> i;
} while (!cin); // cin.good() is not set / cin failed to read 
try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <ctype.h>

bool TFmBatteryConfiguration::IsValidInt(char* x)
{
	bool Checked = true;

	int i = 0;
	do
	{
		//valid digit?
		if (isdigit(x[i]))
		{
			//to the next character
			i++;
			Checked = true;
		}
		else
		{
			//to the next character
			i++;
			Checked = false;
			break;
		}
	} while (x[i] != '\0');

	return Checked;
}


What you do basically is that check every single character in the input looking for any "invalid digit".

hope that helps
Last edited on
Your method doesn't work for negative numbers.

Another way, extract ( >> ) a double, and if it doesn't equal itself casted as an int, then it isn't an integer.
Doesn't cin set a failbit if the input doesn't match the type, already?
@ResidentBiscuit
Yes, but the problem is that the number before the dot in the double input is an integer so it doesn't fail. The dot and everything after it is left in the stream.

I guess you could solve it by first reading the integer number as usual. Then read the rest of the line with std::getline and check that it only contains white space.
Last edited on
@LowestOne: you can put a test for "-" in front of the number for negative number. it should be piece of cake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>

int main()
{
    double teger;
    int teger2;
    do
    {
        std::cout << "enter an int" << std::endl;
        std::cin >> teger;
        std::cin.ignore();
        std::cin.clear();
        std::cout << "you entered: " << teger << std::endl;
        teger2 = teger;
        std::cout << "the int of that is: " << teger2 << std::endl;
        std::cout << std::endl;
        if (teger != teger2) std::cout << "Sorry, that isn't an int, try again." << std::endl;
        std::cout << std::endl;
    } while (teger != teger2);
    std::cout << "congrats, you passed the int test" << std::endl;
    return 0;
}
Last edited on
That's the way I do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int getInt(void)
{
  double num;

  cin >> num;  // This needs validation too.
  cin.ignore(80, '\n');
  while (num != static_cast<int>(num))
  {
    cout << "Sorry, that isn't an integer: ";
    cin >> num;
    cin.ignore(80, '\n');
  }
  cin.ignore(80, '\n');
  return static_cast<int>(num);
}


When >> expects a number and you give it a non-number, you set the fail bit of cin, so you can do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
double getNum(void)
{
  double num;
  while (!(cin >> num))
  {
    cin.clear();
    cin.ignore(80, '\n');
    cout << "Sorry, not a number: ";
  }
  cin.ignore(80, '\n');
  return num;
}

// Which makes getInt() like this:

int getInt(void)
{
  double num = getNum();
  while (// not an integer...
  return num;
}
Last edited on
closed account (j2NvC542)
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
To truly ignore everything left in cin. Just as a tip for everyone here.
cin.sync() does just that as well.
@Texan40
cin.sync() doesn't work the same in all implementations so it's not a cross platform solution.
I like to use something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <sstream>

int get_int(char *message)
{
	using namespace std;

	int out;
	string in;

	while(true) {

		cout << message;
		getline(cin,in);
		stringstream ss(in); //covert input to a stream for conversion to int

		if(ss >> out && !(ss >> in)) return out;
		//(ss >> out) checks for valid conversion to integer
		//!(ss >> in) checks for unconverted input and rejects it

		cin.clear(); //in case of a cin error, like eof() -- prevent infinite loop
		cerr << "\nInvalid input. Please try again.\n"; //if you get here, it's an error
	}
}

int main()
{
	int i = get_int("Please enter an integer: ");
}


Input examples (no quotes):
"a123" -> rejected (leading 'a')
"123a" -> rejected (trailing 'a')
"12 3" -> rejected (space and 3)
"-123" -> allowed
"--123" -> rejected (extra '-')
"2147483648" -> rejected (out of int's range)
"12345.678" -> rejected (decimal)

Note: leading/trailing whitespace is NOT rejected, by design.
Topic archived. No new replies allowed.