gpt4 book ai didi

c - fflush(stdin) 函数不起作用

转载 作者:行者123 更新时间:2023-11-30 17:12:21 25 4
gpt4 key购买 nike

我似乎无法弄清楚这段代码有什么问题:

#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", &sect_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", &current_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。然而,输入带有空格的字符串会导致错误,并且程序假定在下一个提示中输入空格后面的单词。

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 函数不会将数据从输入流中刷新;相反,它用于将输出流中缓冲的数据推送到目的地。这已记录在案here 。如this earlier SO question中所示,尝试使用 fflush(stdin) 会导致未定义的行为,因此最好避免它。

如果您想从用户完成输入字符时输入的返回字符中删除换行符,请考虑以下内容:

scanf("%c%*c", &sect_cat);

这将吃掉换行符,而不是将其留在 stdin 中。

希望这有帮助!

关于c - fflush(stdin) 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com