...
This noncompliant code example attempts to remove the trailing newline (\n) from an input line.
| Code Block | ||||
|---|---|---|---|---|
| ||||
char buf[BUFSIZ + 1];
if (fgets(buf, sizeof(buf), stdin)) {
if (*buf) { /* see FIO37-C */
buf[strlen(buf) - 1] = '\0';
}
}
else {
/* Handle error condition */
}
|
...
This compliant solution uses strchr() to replace the newline character in the string (if it exists). The equivalent solution for fgetws() would use wcschr().
| 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 */
}
|
...