First fgets() call being skipped during input?

2019-06-06 07:12发布

问题:

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.

回答1:

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 subsequent fgets() 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.



回答2:

getc will return the character, but then new line character is still in the stdin buffer, so your first call to fgets gets a line with just a new line character.



标签: c stdin fgets