0

I found when I use the fgets function like so:

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

int main(void)
{
    char str[10];
    fgets(str, 5, stdin);

    printf("%s", str);
    system("PAUSE");

    return 0;
}

If I input a 123456789, it will output a 1234. That's 4 characters - not the 5 I have defined in the function. What is happening to the fifth character?

edit: title updated

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Invisible Hippo
  • 124
  • 1
  • 1
  • 9
  • 2
    fifth character is null character. strings end with null termination in C language – saygins Nov 13 '16 at 21:20
  • @saygins sorry for discarding your edit, but I had a concurrent substantial edit in the works at the same time. and NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character): http://stackoverflow.com/questions/2911089/null-terminating-a-string – Jean-François Fabre Nov 13 '16 at 21:22
  • 1
    see [fgets](http://en.cppreference.com/w/c/io/fgets) (_Reads at most **count - 1** characters from the given file stream_) – BLUEPIXY Nov 14 '16 at 00:30

1 Answers1

0

that's because since C-strings are NUL terminated, fgets takes the string terminator (\0) into account, so if you pass a 5-char buffer, it is safe.

In your code, you should do:

fgets(str, sizeof(str), stdin);

since str is an array with known size.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219