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.
#include <iostream>
usingnamespace 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;
}
elseif (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;
}
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) returnfalse;
for (int c = 0; c < in.length(); c++) {
if (in[c] < '0' || in[c] > '9' && in[c] != '-') returnfalse;
}
returntrue;
}
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.