I'm writing a program that can take computer specifics from the user in manual mode. However, I've run into a bit of a problem.
In this code:
char choice = getc(stdin);
if (choice == 'y' || choice == 'Y')
{
config_file = fopen(config_file_loc, "w");
printf("%s", "Please enter the name of your distribution/OS: ");
fgets(distro_str, MAX_STRLEN, stdin);
fputs(distro_str, config_file);
fputs("\n", config_file);
printf("%s", "Please enter your architecture: ");
fgets(arch_str, MAX_STRLEN, stdin);
fputs(arch_str, config_file);
fputs("\n", config_file);
fclose(config_file);
}
During runtime, the input jumps right from "Please enter the name of your distribution/OS:" to "Please enter your architecture:", leaving distro_str blank.
I've tried flushing stdin and stdout, but those haven't worked.
Thanks for your help.
getc
will return the character, but then new line character is still in thestdin
buffer, so your first call tofgets
gets a line with just a new line character.When you call
getc(stdin)
to get the "choice" character, it reads exactly one character from the input buffer. If the user entered "y" followed by a newline, then the newline will remain in the input buffer, and the subsequentfgets()
call will read that - an empty line - and return immediately.If you wish all input to be line-oriented, then you should call
fgets()
each time, including when reading the "choice" value.