那麼我只學了2個月的C程序設計。我在這裏得到的代碼是解決收銀系統問題。我得到了一些條形碼號碼,項目名稱和價格。收銀員輸入多個條形碼並用F結束後,應顯示具有項目編號,代碼和價格的收據。 這些是我編譯的代碼。但是,我只能輸入一個條碼,程序崩潰。C程序收銀系統
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
typedef struct goods
{
char goods_code[6];
char goods_descrip[20];
float price;
}goodtype;
goodtype goods[13];
strcpy(goods[0].goods_descrip, "Chicken");
strcpy(goods[0].goods_code, "00310");
goods[0].price = 35.00;
strcpy(goods[1].goods_descrip, "Pork");
strcpy(goods[1].goods_code, "00311");
goods[1].price = 20.50;
strcpy(goods[2].goods_descrip, "Beef");
strcpy(goods[2].goods_code, "00322");
goods[2].price = 45.00;
strcpy(goods[3].goods_descrip, "Fish");
strcpy(goods[3].goods_code, "00323");
goods[3].price = 40.00;
strcpy(goods[4].goods_descrip, "Walmart T Shirt");
strcpy(goods[4].goods_code, "00510");
goods[4].price = 75.00;
strcpy(goods[5].goods_descrip, "Walmart Trousers");
strcpy(goods[5].goods_code, "00511");
goods[5].price = 120.00;
strcpy(goods[6].goods_descrip, "Walmart Coat");
strcpy(goods[6].goods_code, "00512");
goods[6].price = 100.00;
strcpy(goods[7].goods_descrip, "Walmart Jumper");
strcpy(goods[7].goods_code, "00513");
goods[7].price = 85.00;
strcpy(goods[8].goods_descrip, "Mug");
strcpy(goods[8].goods_code, "00710");
goods[8].price = 15.50;
strcpy(goods[9].goods_descrip, "Fry Pan");
strcpy(goods[9].goods_code, "00711");
goods[9].price = 200.00;
strcpy(goods[10].goods_descrip, "Bowl");
strcpy(goods[10].goods_code, "00712");
goods[10].price = 25.00;
strcpy(goods[11].goods_descrip, "Dish");
strcpy(goods[11].goods_code, "00713");
goods[11].price = 25.00;
char tempCode[6];
char receiptNM[20], receiptCD[6];
char stop[2] = {"F"};
float receiptPC, ttlcost = 0;
unsigned int i;
printf("Please enter the item code. Type F to finish");
scanf("%s", &tempCode);
while (strcmp(tempCode, stop)){
for (i = 0; i <= 12; ++i){
if (strcmp(tempCode, goods[i].goods_code) == 0){
strcpy(receiptNM, goods[i].goods_descrip);
strcpy(receiptCD, goods[i].goods_code);
receiptPC = goods[i].price;
ttlcost += goods[i].price;
}
else{
printf("This item code does not exist! Try again!\n");
}
printf("Please enter the item code. Type F to finish");
scanf("%s", &tempCode);
}
printf("_____________________________________\n\n");
printf(" THANK YOU FOR VISITING US! \n");
printf("_____________________________________\n");
printf(" Here is your receipt: \n\n");
printf("%10s%20s%10s", "Item", "Code", "Price");
printf("%10s%20s%10.2f\n", receiptNM, receiptCD, receiptPC);
printf("\n_____________________________________\n");
printf(" TOTAL COST:%.2f \n", ttlcost);
}
我正在爲此奮鬥幾個小時,無法修復它。 示例輸出應該是Sample receipt
當我鍵入00310時,程序無法識別它。當我輸入310時,它可以。
此外,當代碼類型不存在時,錯誤消息應該只顯示一次。但在我的程序中,它有12次。
'scanf(「%c」,&tempCode);'掃描單個字符,而不是字符串。也就是說,'tempCode'不會是NUL終止的字符串。所以你不能使用任何字符串函數。 – kaylum
你的輸出是什麼?你期望解釋的是什麼? @ Sam.W – PassionInfinite
另外,建議你學會使用調試器(如果你還沒有的話)。它會爲你節省很多時間。 – kaylum