0

The following code works great:

int main() {
    char inputString[100];
    printf("\nEnter a sentence: ");
    fgets(inputString, sizeof(inputString), stdin);

    printf("\nYou entered: %s\n", inputString);

    return 0;
}

in that it displays the user's sentence on a new line. But as soon as I add in a new scanf() function:

int main() {
        int num;
        char inputString[100];
        printf("Enter a number: ");
        scanf("%d", &num);

        printf("\nEnter a sentence: ");
        fgets(inputString, sizeof(inputString), stdin);
    
        printf("\nYou entered: %s\n", inputString);
    
        return 0;
    }

The program no longer works. Everything set to be printed prints, but it never gives the user an opportunity to enter the sentence. The code just ends after the number is inputted. I don't understand why this is happening, or why this seemingly minor addition causes this error.

  • What happens to the `'\n'` left in `stdin` from the user pressing ENTER following `scanf("%d", &num);`? (hint: `fgets()` stops reading when it encounters a `'\n'` -- another pitfall in using `scanf()`) Add a `getchar()` after `scanf()` to remove it. (better `for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}` – David C. Rankin Oct 27 '22 at 02:47

0 Answers0