Reputation: 179
What I am seeing is that while accepting a string - fgets takes the string till an enter key is pressed, and in the end it DOES NOT replace the enter key with \0 - rather appends \0 to the string including enter key. In comparison, gets_s takes the string till enter key is pressed and in the end - replaces the last enter key with \0.
Is this correct. Please add, correct, confirm. Also does this mean. my string handling operations that operate character by character till they encounter a \0 - will now - with fgets - operate on a newline character as well ?
#include <stdio.h>
#include <conio.h>
int main()
{
char i[32];
printf("Enter a string of size 32 or less characters \n");
gets_s(i, sizeof(i));
//fgets(i, sizeof(i), stdin);
printf("With right justification, field width = 32 and precision = 10 -> i = ||%32.10s||\n", i);
printf("With left justification, field width = 32 and precision = 10 -> i = ||%-32.10s||\n", i);
printf("With right justification, field width = 10 and precision = 32 -> i = ||%10.32s||\n", i);
printf("With left justification, field width = 10 and precision = 32 -> i = ||%-10.32s||\n", i);
_getch();
return 0;
}
Upvotes: 0
Views: 5557
Reputation: 153348
How does fgets treat enter key press?
Just like any other key, other than it is 1 of 4 reasons to stop reading more.
" fgets takes the string till an enter key is pressed, " is a causal explanation.
Let us go deeper
char *fgets(char *s, int n, FILE *stream);
does not read a string as C defines a string (characters up to and including the null character). fgets()
reads a line of characters (characters up to and including the '\n'
). It reads them up to a certain point - leaving the rest for later.
'\n'
is read (and saved).In cases 1, 2 and 3 (if at least something was read), a null character is appended to the input. Now the input is certainly a string and the function return s
. In other cases the function returns (char *) NULL
.
Note the if fgets()
reads null characters, they are treated like any other non-'\n'
.
Enter causes '\n'
: That is a character too.
The '\n'
might need to be discarded for later processing. In that case simply lop it off. Since the input might not contain '\n'
, robust code does not rely on its presence. Nor does robust code assume the first character is not a null character.
size_t len = strlen(s);
if (len > 0 && s[len-1] == '\n') {
s[--len] = '\0';
}
// OR
s[strcspsn(s, "\n")] = '\0';
OP's explanation of gets_s()
has similar detail missing in OP's desciption: special functionality on buffer full, end-of-file and error.
Upvotes: 2