I'm trying to use fgets to obtain user input from the command line. The code snippet is part of a function that allows users to add new nodes to a singly linked list. As you can see from my code, I use a while loop to keep requesting input from the user (so that he/she can add more than one node). When I run the program, everything is fine the first time. When I try to add a second node, however, the program skips the input request for the first name field. In my command line, I get First name: Last name:
while (go)
{
char first_name[256];
char last_name[256];
char telephone[256];
char address[256];
printf("First name: ");
fflush(stdout);
fgets(first_name, sizeof(first_name), stdin);
//scanf("%s", &first_name);
fflush(stdin);
printf("Last name: ");
fflush(stdout);
fgets(last_name, sizeof(last_name), stdin);
fflush(stdin);
//scanf("%s", &last_name);
printf("Address: ");
fflush(stdout);
fgets(address, sizeof(address), stdin);
fflush(stdin);
//scanf("%s", &address);
printf("Telephone: ");
fflush(stdout);
fgets(telephone, sizeof(telephone), stdin);
fflush(stdin);
//scanf("%s", &telephone);
if (!search_by_all(first_name, last_name, address, telephone))
{
add_entry(first_name, last_name, address, telephone);
printf("Success adding entry! Add another entry? 1 for yes, 0 for no.\n");
scanf("%d", &go);
fflush(stdin);
fflush(stdout);
}
else
{
printf("Error adding entry. Quitting...\n");
break;
}
}
I have looked at similar questions on stackoverflow and other sites, but flushing stdin and stdout don't do the trick for me. Neither does allocating more space in my buffers. Any suggestions? Thanks!