簡體   English   中英

一些fget在C編程中無法工作

[英]some fgets cannot work in C programming

#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)無法工作)我可以知道原因和方式解決這個問題? THKS。

這個序列是一個問題:

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…

您需要使用\\n結束(而不是開始) printf(3)格式字符串或調用fflush(3),因為stdio(3)通常是緩沖的(請參閱setvbuf(3) ...); 所以添加一個fflush(NULL); 在每次調用scanf之前。

您還應該測試scanf(3)的返回(已掃描項目)計數。

另請參閱fgets(3)的文檔。 您可能更喜歡使用getline(3)甚至(在具有它的系統上,例如Linux)使用readline(3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM