1

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

Output:

48 is string sub 0
ERROR NOT A BINARY NUMBER
1
  • without the definition of binary[] this question cannot be answered. Commented Sep 18, 2010 at 3:42

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

np - glad to be of assistance.
1

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 ||.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.