What is the difference between fgets()
and gets()
?
I am trying break my loop when the user hits just \"enter\". It\'s working well with
Drop gets()
and scanf()
.
Create a helper function to handle and qualify user input.
// Helper function that strips off _potential_ \n
char *read1line(const char * prompt, char *dest, sizeof size) {
fputs(prompt, stdout);
char buf[100];
*dest = '\0';
if (fgets(buf, sizeof buf, stdin) == NULL) {
return NULL; // EOF or I/O error
}
// Remove potential \n
size_t len = strlen(buf);
if (len > 0 && buf[len-1] == '\n') {
buf[--len] = `\0`;
}
// Line is empty or too long
if (len == 0 || len >= size) return NULL;
return memcpy(dest, buf, len+1);
}
void enter(void)
{
int i;
for(i=top; i Enter name (ENTER to quit): ",
cat[i].name, sizeof cat[i].name) == NULL) break;
if (read1line(".> Enter Last Name: ",
cat[i].lastname, sizeof cat[i].lastname) == NULL) break;
if (read1line(".> Enter Phone Number: ",
cat[i].phonenum, sizeof cat[i].phonenum) == NULL) break;
if (read1line(".> Enter e-Mail: ",
cat[i].info.mail, sizeof cat[i].info.mail) == NULL) break;
if (read1line(".> Enter Address: ",
cat[i].info.address, sizeof cat[i].info.address) == NULL) break;
}
top = i;
}
Some attributes of fgets()
and gets()
:
fgets()
reads input and saves to a buffer until:
1) The buffer is 1 shy of being full - or -
2) '\n'
is encountered - or -
3) The stream reaches an end-of-file condition - or -
4) An input error occurs.
gets()
does #2 - #4 above except it scans, but does not save a '\n'
.
gets()
is depreciated in C99 and no longer part of C11.