...
This noncompliant code example attempts to remove the trailing new-line (\n
) from an input line. The fgets()
function is typically used to read a new-line terminated-line of input from a stream. It takes a size parameter for the destination buffer and copies, at most, size-1
characters from a stream to a character array.
Code Block | ||||
---|---|---|---|---|
| ||||
char buf[BUFSIZ + 1]; if (fgets(buf, sizeof(buf), stdin) == NULL) { /* Handle error */ } buf[strlen(buf) - 1] = '\0'; |
...
This compliant solution uses strchr()
to replace the new-line character in the string, if it exists. (See rue FIO36-C. Do not assume a new-line character is read when using fgets().)
Code Block | ||||
---|---|---|---|---|
| ||||
char buf[BUFSIZ + 1]; char *p; if (fgets(buf, sizeof(buf), stdin)) { p = strchr(buf, '\n'); if (p) { *p = '\0'; } } else { /* Handle error condition */ } |
...