Positive or negative integers

Hello guys I was wondering how I could allow only integers to be entered. I've already tried it in the code below but when enter I enter a character is tells me that I entered a negative number. Can somebody point out what I'm doing wrong.

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>
using namespace std;

int main()
{
	int x;
		cout << "Please enter an integer: ";
		cin >> x;
	
	if (x>0)
	{
		cout << "The number you entered is positive." << endl;
	}
	else if (x<0)
	{
		cout << "The number you entered is negative." << endl;
	}
	else if (x==0)
	{
		cout << "The number is you entered is 0." << endl;
	}
	else 
	{
		cout << "Invalid integer." << endl;
	}
	
	system ("pause");
	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (!(cin >> x))
{
	cout << "Invalid integer." << endl;
}
else if (x>0)
{
	cout << "The number you entered is positive." << endl;
}
else if (x<0)
{
	cout << "The number you entered is negative." << endl;
}
else
{
	cout << "The number is you entered is 0." << endl;
}

Hello, Thanks for the reply but when I tried your code I had to enter the input 2x now for the message to appear.
Peter87's code is correct. Did you make sure to remove the first "std::cin"?

This is the full code:
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 <iostream>
#include "conio.h"

int main()
{
	int x;
	std::cout << "Please enter an integer: ";

	if (!(std::cin >> x))
	{
		std::cout << "Invalid integer." << std::endl;
	}
	else if (x>0)
	{
		std::cout << "The number you entered is positive." << std::endl;
	}
	else if (x<0)
	{
		std::cout << "The number you entered is negative." << std::endl;
	}
	else
	{
		std::cout << "The number is you entered is 0." << std::endl;
	}
	_getch(); //instead of system pause
	return 0;
}

Use #include <conio.h> and _getch(); instead of system("pause").
Last edited on
Thank you! It worked!

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
#include <iostream>
using namespace std;

int main ()
{
	int x;
	cout << "Please enter an integer; " << endl;
	if (!(cin>>x))
	{
		cout << "Invalid integer" << endl;
	}
	else if (x>0)
	{
		cout << "The number you entered is positive." << endl;
	}
	else if (x<0)
	{
		cout << "The number you entered is negative." << endl;
	}
	else 
	{
		cout << "The number you entered is 0." << endl;
	}
	system ("pause");
		return 0;
}
system("pause") can also be replaced with cin.get(); , but u need to use #include "conio.h"
Note that conio.h is a non-standard header that comes only with some compilers.
Topic archived. No new replies allowed.