"...but gets() no issue about newline"
Note, that although your observation about gets()
being preferable in this case over fgets()
for handling newline, the unfavorable behaviors that come with gets() make it dangerous to use, with the result that "it was officially removed by the 2011 standard." (credit) Even without the
mitigations mentioned below, fgets() is highly preferred over gets()
.
"fgets() goes newline when storing string..." and "...why does fgets() automatically enter a newline for each input of string"
fgets()
does not enter the newline upon reading the line, rather if one exists, the newline is picked up as part of the line when fgets()
called. For example in this case, when using stdin
as the input method, the user clicks the <return>
to finish inputting text. Upon hitting the <return>
key, a
is entered just like any other character, and becomes the last character entered. When the line is read using fgets()
, if the
is seen before any of its other stop reading criteria, fgets()
stops reading, and stores all characters, including
, terminates line with
and stores into the buffer. (If sizeof(buffer) - 1
or EOF is seen first, fgets()
will never see the newline.)
To easily eliminate the
, (or other typical unwanted line endings), use the following single line statements after each of your calls to fgets():
fgets(user.id, ID_SIZE, stdin);
user.id[strcspn(user.id, "
")] = 0;
//fflush(stdin);//UB, should not be called
...
fgets(user.fname, MAX_FNAME_SIZE, stdin);
user.fname[strcspn(user.fname, "
")] = 0;
...
fgets(user.lname, MAX_LNAME_SIZE, stdin);
user.lname[strcspn(user.lname, "
")] = 0;
...
This technique works for truncating any string by searching for the unwanted char
, whether it be "
"
, "
"
, "
"
, etc. When using more than one search character, eg "
"
, it searches until it reaches either the
or the
and terminates at that position.
"This [method] handles the rare buffer than begins with ''
, something that causes grief for the buffer[strlen(buffer) - 1] = '';
[method]." (@Chux - comment section of link below.)
Credit here