If/Else statement issue

I'm writing a simple code for class. Prompts user to enter a number then tells them that number and also states whether is negative or positive. MY issue is , what if the user enters a char ? How can I code that to state they didn't enter a number? If i run my program, and the user enters a char it gives me a weird answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
  using namespace std;

int main()
{
	double num;

	cout << "Please enter a number. "; cin >> num;

	if (num > 0)
	{
		cout << "The number you entered is: " << num << ". This number is positive!" << endl;
	}
	else if (num < 0)
	{
		cout << "The number you entered is: " << num << ". This number is negative!" << endl;
	}
	else
	{
		cout << "The number you entered is 0" << endl;
		return 0;
}
How about:

1
2
3
4
5
6
7
8
else if (num == 0){
cout << "The number you entered is 0!";
}

else {
cout << "What you have entered is not a number";
}

Considering this is a class assignment, you probably don't have to worry about whether the user enters in a number or not. However, you can still check if the user enters a number by doing the following:

1
2
3
4
5
6
7
bool isInteger(std::string in) {
  if (in.length() < 1) return false;
  for (int c = 0; c < in.length(); c++) {
    if (in[c] < '0' || in[c] > '9' && in[c] != '-') return false;
  }
  return true;
}


1
2
3
4
5
6
std::string input;
std::cin >> input:

if (isNumber(input)) {
  ...
}


Though this requires the use of functions and loops which might not have been covered by your class yet. Like I said, you probably don't have to worry about it.
Last edited on
for char you have functions like getc or getchar

there is also a function called isdigit

simply search in references.
Topic archived. No new replies allowed.