首先与fgets()调用输入时被跳过? [英] First fgets() call being skipped during input?
问题描述
我在写一个程序,可以采取计算机细节在手动模式下,用户。不过,我碰到了一点小问题。
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.
在此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);
}
在运行时,输入正确的跳跃,从请输入您的发行/ OS的名称:来请输入您的架构:留下distro_str空白
During runtime, the input jumps right from "Please enter the name of your distribution/OS:" to "Please enter your architecture:", leaving distro_str blank.
我试过冲洗stdin和stdout,但这些都没有奏效。
I've tried flushing stdin and stdout, but those haven't worked.
感谢您的帮助。
推荐答案
当你调用 GETC(标准输入)
来获得选字,它读取一个字符从输入缓冲器。如果用户输入Y后跟一个换行符,则换行符将保留在输入缓冲区,以及随后的与fgets()
通话将读取 - 一个空行 - 并立即返回。
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.
如果您希望所有输入要面向行的,那么你应该叫与fgets()
每次看完选择的价值时,包括
If you wish all input to be line-oriented, then you should call fgets()
each time, including when reading the "choice" value.
这篇关于首先与fgets()调用输入时被跳过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!