~/Usage of fputs, fgets, fflush, and scanf in C

Feb 13, 2019


The fputs function writes a string to the specified file stream. The fgets function reads a line from a file or stdin, including the newline. To clear input or output buffers, fflush is used. scanf reads formatted input, usually from stdin.

Below is a concise example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

int main() {
    char buffer[100];

    // Input with scanf
    printf("Enter a word: ");
    scanf("%99s", buffer); // Reads a word, stops at whitespace
    fflush(stdin); // Clear input buffer (not portable, use carefully)
    fputs("Scanf result: ", stdout);
    fputs(buffer, stdout);
    fputs("\n", stdout);

    // Input with fgets
    printf("Enter a line: ");
    fflush(stdout); // Ensure prompt is displayed
    fgets(buffer, 100, stdin); // Reads a line, includes newline character
    fputs("Fgets result: ", stdout);
    fputs(buffer, stdout);

    return 0;
}

Notes:

For more on safe input, see C input handling.

Tags: [c] [io]