Binary Numbers. Error When Checking to be sure binary input is binary
I'm writing a simple loop to make sure my input is a valid binary. Ex: I want to throw an error when any number higher than one is user input. I know I need to check against the ASCII numbers. What is going on here? I should not be getting an error when I input binary. Any thoughts?
for (int i=0;i<size;i++)
{
printf("%i is string sub %i\n",int(binary[i]),i);
if (int(binary[i]) != 48 || int(binary[i]) != 49)
{
printf("ERROR NOT A BINARY NUMBER\n");
exit(0);
}
}
input:
0101
Ou开发者_如何学Pythontput:
48 is string sub 0
ERROR NOT A BINARY NUMBER
You need to use if (int(binary[i]) != 48 && int(binary[i]) != 49)
- note && rather than ||. As it stood, the if(...)
was effectively if(true)
as binary[i]
could not be both 48 and 49 simultaneously.
You are using the wrong boolean operator. If you read your if statement out loud, this is what it sounds like:
Execute what is inside the if statement if binary[i] is not '0' OR if it is not '1'.
How can it be two things at the same time?
Use &&
instead of ||
.
精彩评论