gpt4 book ai didi

c - 一些 fgets 不能在 C 编程中工作

转载 作者:太空宇宙 更新时间:2023-11-04 05:55:42 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>

int main()
{
int sel_1, sel_2, telno[12], price = 0, sum = 0, i;
char pkg[2], name[10], addrs[30], name_1[50][50], addrs_1[50][50];

printf(" Lunch4You Enterprise\n Delivery Service Subscription System\n");
printf("==========================================================================");
printf("\nPackage that we have:\n 1. Package A: 20days/month(5days/week) - RM60/month");
printf("\n 2. Package B: 12days/month(3days/week) - RM45/month");
printf("\n 3. Package C: 8days/month(2days/week) - RM35/month");

do
{
printf("\nPlease select the package: ");
scanf("%d", &sel_1);
}
while (sel_1 != 1 && sel_1 != 2 && sel_1 != 3);

switch (sel_1)
{
case 1: strcpy(pkg, "A"); price = 60;
break;
case 2: strcpy(pkg, "B"); price = 45;
break;
case 3: strcpy(pkg, "C"); price = 35;
break;
}

printf("\n\nYou have selected Package %s.", pkg);

do
{
printf("\nHow many receiver of lunchbox?: ");
scanf("%d", &sel_2);
}
while (sel_2 > 5 || sel_2 < 1);

sum = sel_2 * price;
printf("\n\nPlease enter the information below:\nName of subscriber: ");
scanf("%s", &name);
printf("\nAddress (Pick-up): ");
fgets(addrs,30,stdin);

for (i = 0; i < sel_2; ++i)
{
printf("Name of receiver (%d): ", i + 1);
fgets(name_1[i], 50, stdin);
printf("Address(Receiver)(%d): ", i + 1);
fgets(addrs_1[i], 50, stdin);
printf("Tel No (%d)", i + 1);
scanf("%d", &telno[i]);
}

printf("\n\nYour information for lunchbox delivery are:");
printf("\nPackage : %s", pkg);
printf("\nPick-up Address: %s", addrs);

for (i = 0; i < sel_2; ++i)
{
printf("\nReceiver %d: %s, %s\n\t\t%d", i + 1, name_1[i], addrs_1[i], telno[i]);
}
printf("\n\nTotal fee: RM%d\n", sum);

return 0;
}

$some fgets 不能工作,它只是跳到下一个 fgets 然后等待用户输入。(在这种情况下,'for 循环'中的 fgets(addrs) 和 fgets(name_1) 不能工作)我能知道吗为什么以及如何解决这个问题?谢谢。

最佳答案

这个顺序是个问题:

scanf("%s", &name);
printf("\nAddress (Pick-up): ");
fgets(addrs,30,stdin);

scanf() 在第一个空白字符处停止,很可能是一个换行符; fgets() 然后读取并包括换行符,因此它不需要等待任何输入,因为输入缓冲区中已经有一个换行符,是 scanf( ) 调用。

您需要阅读 scanf() 之后的换行符。并且您应该在每次输入操作后检查问题。

if (scanf("%s", name) != 1)
…report error…
while ((c = getchar()) != EOF && c != '\n')
;
if (fgets(addrs, sizeof(addrs), stdin) == 0)
…report error…

关于c - 一些 fgets 不能在 C 编程中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27996920/

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