Vorkos Vorkos - 2 months ago 9
C Question

In a while loop, fgets() runs by its self taking in a newline as the input

char theInput[10];
long option;
int innerLoop = 1;
char *dunno;
while(innerLoop == 1){
printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
fgets(theInput, sizeof theInput, stdin);
option = strtol(theInput, &dunno, 10);
if(option == 1){
loop = 0;
innerLoop = 0;
}else if(option == 2){
loop = 1;
outerLoop = 1;
innerLoop = 0;
firstLoop = 0;
}else if(option == 3){
loop = 1;
innerLoop = 0;
outerLoop = 1;
firstLoop = 1;
}else{
printf("\nInvalid input, please try again.\n");
innerLoop = 1;
}
}


The result of this code is that when first ran, it prints the "Type '1' to get" part followed by a line break followed by "Invalid input, please try again." without taking any input from the command line. It then prints the first printf statement again, and then accepts an input and works. It is meant to print the first statement then wait for an input.

Below is the terminal output.

"Type '1' to get your change, '2' to select another item, or '3' to add more funds:
Invalid input, please try again.

Type '1' to get your change, '2' to select another item, or '3' to add more funds: "

Answer

Can you try to flush the stdout?

I 've added the main method if other people would like to have a working example:

#include <stdio.h>

int main () {
  int loop = 0;
  int outerLoop = 0;
  int firstLoop = 0;

  char theInput[10];
  long option;
  int innerLoop = 1;
  char *dunno;
  while(innerLoop == 1){
    printf("\nType '1' to get your change, '2' to select another item, or '3' to add more funds: ");
    fflush(stdout);
    fgets(theInput, sizeof theInput, stdin);
    option = strtol(theInput, &dunno, 10);
    if(option == 1) {
      loop = 0;
      innerLoop = 0;
    }else if(option == 2){
      loop = 1;
      outerLoop = 1;
      innerLoop = 0;
      firstLoop = 0;
    }else if(option == 3){
      loop = 1;
      innerLoop = 0;
      outerLoop = 1;
      firstLoop = 1;
    }else{
      printf("\nInvalid input, please try again.\n");
      innerLoop = 1;
    }
  }
}

Before adapting your source code, can you try running this example in isoltion and to see if you have the expected results?