Search code examples
cwhile-loopgets

while loop gets() twice in C


I know that this while loop issue is very common, and it is usually caused by a newline in a input stream. However, I wasn't able to fix my while loop, and I don't really understand why it's happening in my case.

Consider the following example:

 int main()
 {
   int option = -1;
   char buffer[100];
   while (option != 10)
    {
     while(printf("Enter menu choice: \n"), gets(buffer), option < 0)
           {
             some code here dealing with buffer and assigning input to option...
           }
     printf("something\n");
     }
    return 0;
  }

Ignore the implementation of this code (e.g store the input in integer instead of string, etc.) as it's just a simplified version of my case for while loop. What concerns me is then I have to enter the number twice before it actually goes through the loop.

Output:

Enter menu choice: 1

Enter menu choice: 1

All lights are turned on Light settings: 1111 1111 1111 1111

I am not sure why it's happening in this case...Thanks!

UPDATE: Thank you for your answers. I have fixed code by rewriting my while() condition

while(printf("\nEnter menu choice: \n"), gets(buffer),  option = checkMenuOption(buffer), option < 0 && strcmp(buffer, ""));

Solution

  • The printf() and the gets() are within the while test, before the evaluation of option.

    In fact, with the current behavior you don't actually have to enter the number twice: You have to enter the number once and then type anything so gets() will return.

    Edit: I added a few details on is how it runs:

    • Instruction pointer reaches the very beginning of the while statement, begins evaluating its condition
      • calls printf()
      • calls gets()
      • evaluates option < 0, which is true.
    • Body of the while statement
      • code parses string, sets option to a value above zero.
    • Instruction pointer is looped back to evaluating the condition
      • calls printf()
      • calls gets()
      • evaluates option < 0, which is false.
    • while loop terminates
      • calls printf("something\n");

    It's visible here that the buffer, once filled by gets(), is only read by the code in the first iteration, and is ignored on the second one.