Hello, I am creating a gradebook calculator. I am trying to make it so that anything entered for Grade1 has to be a number. Is there a variable or value I can use to represent all numbers to replace x?
std::cout << "Welcome to the Grade Calculator. What is your first number grade? " << std::endl;
std::cin >> Grade1;
if (Grade1 != x)
std::cout << "That is not an acceptable number. Please double-check your typing and try the program again." << std::endl;
No. There is a numerical limitations file, so that things that cannot be represented (like 1 million factorial) in standard variable types can be checked somewhat.
But you are asking for a logical test in a single value, and that isnt possible. Most likely, there is a valid range of input, like 0 to 100, or if you allow bonus points, maybe 0 to 125 where these are typical school grades representing a %.
There are no unsigned floating point types, so if you need decimal accuracy, you need a double.
If you are working in whole numbers, an unsigned char will work, an you can check it:
if(Grade1 <125 && Grade1 >= 0)
.... handle error..
you can do the same for floating point... just be a little more precise (no real effect but its better code as it tells the user that Grade1 should be a floating point).
if(Grade1 < 125.0 && Grade1 >= 0.0)
with a bit of odd coding you could probably express this as a value such that your example code would work, but it would be a strange thing to do.
constint MIN_GRADE = 0 ;
constint MAX_GRADE = 100 ;
int grade_1 ;
std::cout << "Welcome to the Grade Calculator. What is your first number grade?\n""please enter a value in the range [" << MIN_GRADE << ',' << MAX_GRADE << "]: " ;
if( std::cin >> grade_1 ) // if the user entered a valid integer
// proceed with processing the input
if( grade_1 >= MIN_GRADE && grade_1 <= MAX_GRADE ) // the value within range
// do something with the entered grade
else // integer was input, but it is out of range
std::cout << "the value you entered is out of range\n""please try the program again.\n" ;
return 1 ;
else // the user did not enter a sequence of characters that formed an integer
std::cout << "That is not an acceptable number.\nPlease double-check your"" typing and try the program again.\n" ;
return 1 ;