我刚开始使用 C,我编写了一个非常简单的程序,它接受员工 ID、工作时间和薪水,并输出所赚取的工资和给定的 ID。
我正在使用 fgets 捕获 ID,但是,当我输入比指定缓冲区大小(此处为 10)长的字符串时,我的程序似乎“崩溃”了。它在同一行打印接下来的两个 printf,跳过第一个的输入,这显然会破坏程序。
当使用 fgets 捕获的 ID <= 缓冲区大小时,它工作正常。关于问题是什么有点困惑。 FWIW 我在 GNU GCC 编译器中使用代码块。
谢谢。
#include <stdio.h>
int main()
{
// Initialize variables
char ID[11];
float hrs, sal;
// Get Employee's ID from user input
printf("Input the Employee's ID(Max. 10 chars): ");
fgets(ID, sizeof(ID), stdin);
// Get working hours as float from user input
printf("Input the working hrs: ");
scanf("%f", &hrs);
// Get hourly salary as float from user input
printf("Salary amount/hr: ");
scanf("%f", &sal);
// Print Employee's ID
printf("Employee's ID: %s", ID);
// Print wage based on hours worked and salary
printf("Salary = U$ %.2f", sal * hrs);
return 0;
}
最佳答案
原因是,如果行的其余部分大于传递的缓冲区,则它不会被 fgets()
获取,因此保留在标准输入文件流的输入缓冲区中;随后 scanf()
的转换失败。
您必须检测这种情况(例如,通过检查您刚刚读取的字符串中的最后一个字符是否不是换行符)并清空输入缓冲区直到下一个换行符,例如通过调用 getchar ()
在循环中直到换行符(或 EOF)。然后调用 scanf()
。
示例代码(未经测试且 EOF 检查仍然缺失):
fgets(ID, sizeof(ID), stdin);
if (ID[strlen(ID)-1] != '\n') {
while (getchar() != '\n')
;
}
并且记得检查您的 scanf()
调用的返回值以查看转换是否成功!
关于c - 当我的 fgets 输入超过指定的缓冲区大小时,我的(非常简单的)程序似乎表现出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54208148/