[英]First fgets() call being skipped during input?
我正在编写一个程序,可以在手动模式下从用户那里获取计算机的详细信息。 但是,我遇到了一个问题。
在此代码中:
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);
}
在运行时,输入从“请输入发行版/操作系统的名称:”跳到“请输入您的体系结构:”,而distro_str为空。
我试过冲洗stdin和stdout,但是没有用。
谢谢你的帮助。
当您调用getc(stdin)
以获取“选择”字符时,它将从输入缓冲区中精确读取一个字符。 如果用户输入“ y”后跟换行符,则换行符将保留在输入缓冲区中,随后的fgets()
调用将读取该内容(空行)并立即返回。
如果希望所有输入都面向行,则每次(包括在读取“ choice”值时fgets()
都应调用fgets()
。
getc
将返回该字符,但是新行字符仍在stdin
缓冲区中,因此您对fgets
的第一次调用仅获得了一个新行字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.