0

I have the following piece of code. I want a user to enter a or r and continue executing the program, or try to get user input if he enters something else.

But my problem is, when I enter an illegal value the program shows the message twice, and not just once. How can I make the message only ever show once?

label: 
    puts ("a/r?"); 
    c = getchar (); 
    if (c != 'a' || c != 'r') 
      goto label; 
esthepiking
  • 1,647
  • 1
  • 16
  • 27
Tomasz Tarka
  • 111
  • 3
  • This earlier [SO post](http://stackoverflow.com/questions/19059730/cannot-figure-out-how-to-use-getchar-in-c) should help – vmachan Jan 05 '16 at 22:45
  • 1
    This is an awful usage of `goto`. Use 70ies BASIC if you insist on using it. Otherwise use a loop statement in any "modern" (i.e. post 70ies) language. – too honest for this site Jan 06 '16 at 00:04

2 Answers2

2

You should use: if (c != 'a' && c != 'r')

Also to avoid duplicated messages you should replace getchar() with scanf("%c", &c)

marian0
  • 664
  • 6
  • 15
0

If the user enters a, they have to press the enter key on their keyboard for the input to register. This key leaves a newline character in standard input and therefore that character is read the second time around and the test fails again.

The test fails for any input because you are trying to have the input be two things at the same time. You have to use && instead of || in order to just check if the input is either one of the characters you are looking for. I know this sounds like it should be the other way around, but that is definitely not the case as you have observed.

smac89
  • 39,374
  • 15
  • 132
  • 179