---
tags: notes, c, functions
---
# C: input functions: why fgets(), not scanf()
last edition:2020/02/11
## ```fgets()``` (recommended)
**f** stands for file, **get** stands for requiring and **s** stands for string.\
This function is safer then `scanf(%s, str)` because the maximum size `n` is assigned in `fgets()`.
<p> </p>
### Declartion
```cmake=c
char *fgets(char *str, int n, FILE *stream)
```
<p> </p>
### Parameters
* `char *str`This is the pointer to an array where the string read is stored.
* `int n` This is the maximum number of characters to be read (including the final null-character). Usually, `n` is the length of `str`.
* `FILE *stream` This is the pointer to a FILE object that identifies the stream where characters are read from. e.g. `stdin`.
<p> </p>
### Returns Value
On success, the function returns the same `str` parameter. If the `EOF`(end of file) is encountered and no characters have been read, the contents of `str` remain unchanged and a `NULL` pointer is returned. If an error occurs, a `NULL` pointer is returned.
<p> </p>
### Behavior
The function reads a line from the specified stream and stores it into the string pointed to by `str`. It stops when either `(n-1)` characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
When `FILE *stream=stdin` and the function returns non-NULL pointer, then `str` has the following contents:\
`str[]:o, o, o, o,... 10, 0, x, x, x...`\
where `o, o, o, o,...` are the characters read from the `FILE stream`; `10` is *line-feed* of ascii-code; `0` is null character `\0`; `x, x, x...` are the original contents in the `str[]`.
<p> </p>
## `scanf()`
When reading
### Declartion
```cmake=c
int scanf(const char *format, ...)
```
for reading string:`scanf("%s", &str)`
<p> </p>
### Parameters
<p> </p>
### Returns Value
<p> </p>
### Behavior
<p> </p>