Home How to read safely from stdin in C
Post
Cancel

How to read safely from stdin in C

Ah, C and strings. :confounded:

When reading from stdin, we can use fgets(str, n, stdin) to read at most n - 1 characters into a char array pointed to by str. We can also create a utility function to replace the newline character \n with the null terminator \0.

The following is inspired from C Primer Plus by Stephen Prata, sixth edition, listing 11.10:

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

// Read at most `n` characters (newline included) into `str`.
// If present, the newline is removed (replaced by the null terminator).
void s_gets(char* str, int n)
{
    char* str_read = fgets(str, n, stdin);
    if (!str_read)
        return;

    int i = 0;
    while (str[i] != '\n' && str[i] != '\0')
        i++;

    if (str[i] == '\n')
        str[i] = '\0';
}

int main()
{
    char my_string[10];
    s_gets(my_string, 10);
    printf("my_string = %s\n", my_string);
}

If we run the above program with the input test 12345, we obtain a char array of 9 characters followed by the null terminator \0:

1
my_string = test 1234
This post is licensed under CC BY 4.0 by the author.

Implementing a vector in C

Bitwise nuggets: convert an integer to a binary string

Comments powered by Disqus.