Confused with this bool concept.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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.
Last edited on
You have a typo on line 4. Look carefully at the condition of your loop.

-Albatross
that was a typo, but besides that...... the code works fine. But I just dont understand how the negation makes it work.
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'.

-Albatross
Last edited on
If tmp[i] is NOT greater than or equal to 48 AND tmp[i] is NOT lower than or equal to 57.
Return false.
Thank you guys for your reply.

Honestly what UK MARINE said is how I looked at it.

But i thought

"!=" - NOT

"!" = NEGATION meaning if 0 then its 1.... and vice versa.

Am I not correct!?

and thanks RABBIT!
Last edited on
!= is better translated to English as "is not equal to".

-Albatross
Topic archived. No new replies allowed.