Search code examples
cfgets

fgets inside the while loop


I'm having an issue with fgets because it is returning \n on the first time it enters the while loop right after the k input. Since I'm already inside the while loop and my #1 try as already been written, how do I deal with this?

int main() {
    char r;

    printf("How to input?\n");
    printf("Keyboard ([K])\n File ([F])\n Leave ([E])\n");
    scanf("%c", &r);

    if (r == 'k' || r == 'K') {
        printf("\nKeyboard\n");
        opcaoTeclado();
    } else {
       // stuff
    }
}

void opcaoTeclado() {
    int try = 0;
    char inputline[161];

    while (try <= 10) {
        printf("\n#%d try\n ", try);
        fgets(inputline, 160, stdin);
        try++;
    }
}

Solution

  • After the call to scanf(), there's a newline in the input which is read by the first call fgets(). fgets() stops reading input when it encounters a newline \n. Hence, it doesn't read any input.

    Add a call to getchar(); right after scanf() to consume the newline.

    Or you can also use a loop to consume if there are multiple chars in the input.

    int c;
    
    while((c= getchar()) != '\n' && c != EOF); 
    

    In general, it's best to avoid mixing scanf() with fgets(). You can use fgets() instead of scanf() and parse the line using sscanf() which is less prone.