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

3
  • 2
    fifth character is null character. strings end with null termination in C language Commented Nov 13, 2016 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): stackoverflow.com/questions/2911089/null-terminating-a-string Commented Nov 13, 2016 at 21:22
  • 1
    see fgets (Reads at most count - 1 characters from the given file stream) Commented Nov 14, 2016 at 0:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.