bool isNumber = true;
for (int i = 0; i < tmp.length(); i++)
{
if (!(tmp [i] >= 48 && tmp[i] <= 57))
isNumber = false;
}
if (isNumber)
cout << "Number entered properly " << endl;
else
cout << "Number wasn't entered properly " << endl;
}
This bool concept is confusing me...... this code is basically checking to make sure input isn't any letters only numbers. Why is "negation" needed in the checking part to work??
From my understanding what I am seeing is, if I enter a number it gets negated to FALSE??? But when I run it, the code works fine. I'm not understanding the concept.
Let's dissect the condition of that if statement step by step.
The range of ASCII values from 48 to 57, inclusive, represent base-10 digits. (tmp [i] >= 48 && tmp[i] <= 57) evaluates to true if tmp[i] is a character that represents a digit, and false otherwise.
If that was all that you had in your if statement's condition, then the if statement would run whenever tmp[i] contains a digit. isNumber would get set to false, and your program would report that the string is not a number... because it contains at least one digit. That doesn't make much sense.
The negation inverts that. If tmp[i] is not a digit, the if statement runs and isNumber gets set to false because the program found a character in your string that is not a digit.
Another way of writing that condition would be tmp[i] < '0' || tmp[i] > '9'.