私は車の購入をシミュレートするプログラムを書いています。プログラムはうまく動作しますが、購入が完了してプロンプトに名前を入力すると、gets()
は入力を検索しません。ここに私のコードです。gets();関数はCの2番目のループの入力を待っていません
#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();
}
使用しているオペレーティングシステムはどれですか?また、 'gets()'関数は本質的に安全でないため、以前は廃止されていたことを指摘したいと思います。おそらく 'scanf()'や 'gets_s()'と交換してください。 – paulotorrens
Windows 10. _s関数を認識しないオンラインコンパイラを使用しています。データ消失の恐れがない場合(つまり、顧客が姓と名字を入力した場合、scanfは最初に読み込む)、scanfを使用します。 –
プログラムはどのように終了するはずですか? – jwdonahue