获得();函数不等待C中第二个循环的输入

时间:2017-11-25 06:05:33

标签: c scanf gets

我正在编写一个模拟购买汽车的程序。该程序在第一次运行时运行良好,但在完成购买并且提示要求输入名称后,gets()不会搜索输入。这是我的代码。

#include <stdio.h>

int i;
int j=1;
int prices[5] = { 24000,28000,25000,20000,120000 };
int invent[5] = { 5,2,3,8,2 };
int purchased[5] = { 0, 0, 0, 0, 0 };

int main()
{
    char name[50];

    printf("Welcome to Buy-a-Car!\nPlease enter your name:\n");
    gets(name);
    printf("Welcome, %s. Here is our available inventory.\n", name);
    sale();
    return 0;
}

void sale()
{
    while (i>0, j != 0) {
        printf("1. Toyota Camry      %d  %d\n2. Honda CRV         %d  %d\n3. Honda Accord      %d  %d\n4. Hyundai Elantra   %d  %d\n5. Audi R8           %d %d", invent[0], prices[0], invent[1], prices[1], invent[2], prices[2], invent[3], prices[3], invent[4], prices[4]);
        printf("\nWhich car would you like to purchase?\n");
        scanf("%d", &i);
        i = i - 1;
        printf("How many would you like to purchase?\n(Note: To checkout, please press 0.)\n");
        scanf("%d", &j);
        if (j > invent[i])
            printf("I'm sorry, that number is insufficient. Please try again.\n");
        else
            invent[i] = invent[i] - j;
        purchased[i] = j;
    }
    checkout();
}
void checkout()
{
    printf("Review of transaction:\n1. Toyota Camry     %d  %d\n2. Honda CRV        %d  %d\n3. Honda Accord     %d  %d\n4. Hyundai Elantra  %d  %d\n5. Audi R8          %d %d", purchased[0], prices[0], purchased[1], prices[1], purchased[2], prices[2], purchased[3], prices[3], purchased[4], prices[4]);
    int total;
    for (i = 0; i < 5; i++)
    {
        total = total + (purchased[i] * prices[i]);
    }
    printf("\n\nTotal: %d\n\n\n", total);

    j = 1;
    int purchased[5] = { 0, 0, 0, 0, 0 };
    main();
}

2 个答案:

答案 0 :(得分:0)

这是因为&#39; \ n&#39;使用scanf后缓冲区中的char,使用scanf(&#34;%d%* c&#34;,&amp; var); %* c会阻止&#39; \ n&#39;使用获取时跳过行

获取不安全,使用fgets(&amp; str,sizeof(str),stdin);

答案 1 :(得分:0)

运行scanf()后,Enter(以及之前的任何内容)仍在输入缓冲区中。你可以这样清除它:

scanf("%*[\n]%*c");

while( getchar() != '\n' );

现在gets()不会返回空字符串。但无论如何,非常不鼓励使用它。请改用fgetsscanf("%[^\n]")

fgets(name, sizeof(name), stdin);
// or
scanf("%[^\n]", name);

此外,不要在程序的任何位置致电main() 。它的行为是不确定的。你可以将整个东西包装在另一个函数中,并使用循环。一个无休止的递归调用肯定会最终炸毁堆栈。