fflush(stdin)函数不起作用 [英] fflush(stdin) function does not work
问题描述
我似乎无法弄清楚这段代码出了什么问题:
I can't seem to figure out what's wrong with this code:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
#define TRUE 1
#define FALSE 0
char sect_cat;
char customer_name[MAX];
char customer_number[MAX]; /* error handling is easier */
int prev_unit = 0;
int current_unit = 0;
int consumed = 0;
int set = FALSE;
float init_bill;
float tax;
float total_bill;
void get_userinfo()
{
printf("Enter sector category: ");
scanf("%c", §_cat);
printf("Enter customer name: ");
fflush(stdin);
scanf("%sn", &customer_name);
set = FALSE;
while (set == FALSE)
{
printf("Enter customer number: ");
fflush(stdin);
scanf("%s", customer_number);
int i;
int error;
for (i=0, error=0; i<strlen(customer_number); i++)
{
if (isdigit(customer_number[i]))
{
}
else
{
error = 1;
}
}
if (error == 0)
{
set = TRUE;
}
else
printf("ERROR: Only numbers are allowed\n");
}
printf("Enter previous unit: ");
fflush(stdin);
scanf("%d", &prev_unit);
set = FALSE;
while (set == FALSE)
{
printf("Enter current unit: ");
fflush(stdin);
scanf("%d", ¤t_unit);
if (prev_unit > current_unit)
{
printf("ERROR: Current unit must be larger than previous unit\n");
}
else
set = TRUE;
}
consumed = current_unit - prev_unit;
}
int main()
{
/* Introduce program to users */
printf("\nThis program computes your electric bill based on these sector categories\n\n");
printf("\tResidential(R)\n");
printf("\tIndustrial(I)\n");
printf("\tCommercial(C)\n\n");
printf("Press any key to continue...");
fflush(stdin);
getchar();
#################### 编辑
应用templatetypedef的解决方案,该程序现在等待用户输入customer_name.但是,输入带空格的字符串会导致错误,并且程序假定在空格后的单词是为下一个提示输入的.
#################### edit
Applying templatetypedef's solution, the program now waits for user input for the customer_name. However entering a string with a space leads to an error, and the program assumes that the word after the space is input for the next prompt.
Enter sector category: r
Enter customer name: George of the Jungle
Enter customer number: ERROR: Only numbers are allowed
Enter customer number: ERROR: Only numbers are allowed
Enter customer number:
推荐答案
fflush
函数不会从输入流中刷新数据;它不会从输入流中清除数据.相反,它用于将输出流中缓冲的数据推送到目标.在此处中对此进行了记录.如此早期的SO问题所示,尝试使用fflush(stdin)
会导致未定义的行为,因此最好避免它.
The fflush
function does not flush data out of an input stream; it is instead used to push data buffered in an output stream to the destination. This is documented here. As seen in this earlier SO question, trying to use fflush(stdin)
leads to undefined behavior, so it's best to avoid it.
如果您想吃掉用户输入字符后输入的返回字符中的换行符,请考虑以下内容:
If you want to eat the newline from the return character entered when the user finished typing in their character, instead consider the following:
scanf("%c%*c", §_cat);
这会吃掉换行符,而不是留在stdin
中.
This will eat the newline rather than leaving it in stdin
.
希望这会有所帮助!
这篇关于fflush(stdin)函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!