试图理解不同的输入方式在 C 中是如何发生的,但是 fgets() 倾向于跳过



我是C的新手,并试图了解不同的输入是如何工作的。我编写了这段代码来尝试getChar((,sscanf((和fgets((。我的第一个 fgets(( 工作得很好,但在我要求用户输入日期后它会跳过第二个。我是否以不应该使用它们的方式使用这些函数。有什么可能的方法可以解决这个问题。

此外,对于某些场景,是否有任何其他接收用户输入的方法会更有益。

#include <stdio.h>
#define MAX 12
#define MAX_DATE 100
int main(int argc, const char * argv[]) {
char buf[MAX];
char date[MAX_DATE];
char day[9], month[12];
int year;
printf("This code shows various ways to read user input and also how to check for inputn");
printf("Enter a String less than 11 characters for input: ");
fgets(buf, MAX, stdin); //stdin is used to indicate input is from keyboard
printf("Enter a char: ");
char inputChar = getchar(); //gets next avalible char
printf("nThe char you entered is: "); putchar(inputChar); //puts char prints a char
printf("nsscanf allows one to read a string and manupilate as needed.n");
printf("nEnter a date as follows: Day, Month, Year");
fgets(date, MAX_DATE, stdin);
sscanf(date, "%s, %s, %d", day, month, &year);
printf("nFormatted values as follows... n");
printf("day: %sn", day);
printf("month: %sn", month);
printf("year: %dn", year);
return 0;
}
/*
Output for the code:
This code shows various ways to read user input and also how to check for input
Enter a String less than 11 characters for input: hey
Enter a char: a
The char you entered is: a
sscanf allows one to read a string and manupilate as needed.
Enter a date as follows: Day, Month, Year
Formatted values as follows... 
day: 
month: 
year: -1205589279
Program ended with exit code: 0
*/

您的第二个fgets没有被跳过。它正在获取您生产线的其余部分。

在您的示例中,当"输入字符:"提示时,您输入"a"后跟换行符。getchar得到"a"字符。fgets从紧随其后的字符开始,这意味着它正在读取"a"之后的换行符并返回。

如果您在getchar()之后调用fgets(buf, MAX, stdin);以丢弃该行的其余部分,则程序将按预期工作。

@contrapants很好地解释了"跳过第二个"的原因。 当用户键入Enter时,getchar()读取'a',然后fgets()读取'n',而无需等待其他输入。

对于学习者,我建议仅使用fgets()进行输入。

printf("Enter a char: ");
fgets(buf, sizeof buf, stdin);
char inputChar = 0;
sscanf(buf, "%c", &inputChar);

我是否以不应该使用它们的方式使用这些函数。

在未确保没有溢出的情况下读取缓冲区时会出现附带问题。 使用宽度限制。

char day[9], month[12];
//sscanf(date, "%s, %s, %d", day, month, &year);
int count = sscanf(date, "%8s , %11s , %d", day, month, &year);
if (count != 3) {
Handle_unexpected_input_somehow();
}  

相关内容

最新更新