A newline remains after a typical scanf call

suggest change

Most scanf conversions consume a token but leave the following character in the input stream. After %d reads 42, for example, the newline remains. A subsequent call to fgets reads that newline as an empty line instead of reading the next line of text.

Avoid mixing token-oriented and line-oriented input when possible. Read each line with fgets, check whether the read succeeded, and parse the line separately:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char number_line[128];
    char text[128];

    if (fgets(number_line, sizeof number_line, stdin) == NULL ||
        fgets(text, sizeof text, stdin) == NULL) {
        fputs("Input error\n", stderr);
        return EXIT_FAILURE;
    }

    errno = 0;
    char *end;
    long number = strtol(number_line, &end, 10);
    if (errno != 0 || end == number_line || (*end != '\n' && *end != '\0')) {
        fputs("Invalid integer\n", stderr);
        return EXIT_FAILURE;
    }

    text[strcspn(text, "\n")] = '\0';
    printf("%ld \"%s\"\n", number, text);
    return EXIT_SUCCESS;
}

If existing code must use scanf, check its return value and explicitly discard the rest of the line before calling fgets:

int number;
if (scanf("%d", &number) != 1) {
    /* Handle invalid input. */
}

int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
    /* Discard the remainder of the line. */
}

This discard loop deliberately removes everything after the converted value on that line. That may not be appropriate if the remaining characters are meaningful input.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents