-1

Does anybody have any idea why this always loops for values different than 1 or 0,and also how can i avoid the endless loop in case of giving a character as input?

#include <stdio.h>

int a;

main()
{
    do 
{
    puts("Give 1 or 0 for input:");
    scanf("%d",&a); 
}   while(a!=0 || a!=1);

printf("\n%d",a);
return 0;

}

bazuka
  • 7
  • 1

1 Answers1

3

The only way for the loop to terminate is if both a!=0 and a!=1 are false. Or in other words: it can only end when a == 0 and a == 1 at the same time. That is of course impossible, so the loop never terminates.

If you want to loop to terminate when the user inputs 1 or 0, then you need a logical and operator there:

do 
{
    puts("Give 1 or 0 for input:");
    scanf("%d",&a); 
} while(a!=0 && a!=1);

Aside from that, you really must check the return value of scanf, and purge the input stream in case of failure. If you input a character, then scanf will signify it failed, but leave the character in the input stream. The subsequent iterations will just get stuck on trying to read that character.

One way to do so is with scanf itself and the %*s format specifier.

do 
{
    puts("Give 1 or 0 for input:");
    int read_res = scanf(" %d",&a); 
    if (read_res != 1)
      scanf("%*s");
} while(a != 0 && a != 1);

The asterisk in the format string means scanf will still match any non white-space character and purge them from the stream, but will not attempt to assign them into anything (so no extra parameter is required). I also added a leading white-space to %d in order to disregard any leading white-spaces before the number.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458