所以這是我的代碼,而且......
#include <stdio.h>
int main()
{
int order, stock;
char credit;
printf("\nEnter order value: ");
scanf("%d", &order);
printf("Enter credit (y/n): ");
scanf("%s", &credit);
printf("Enter stock availabilty: ");
scanf("%d", &stock);
if (order <= stock && credit == 121 || credit == 89)
{
printf("Thank you for ordering from us, the items will be shipped soon.\n\n");
}
else if (credit == 78 || credit == 110)
{
printf("Your credit is insufficient, hence as per company policy we cannot ship your ordered items.\n\n");
}
else if (order > stock && credit == 121 || credit == 89)
{
printf("We're falling short on supply, hence we'll ship the items we have in stock right now.\nThe remaining balance will be shipped as soon as stock arrives.\n\n");
}
else
{
printf("Invalid data.");
}
return 0;
}
...這是我的意見:
Enter order value: 12
Enter credit (y/n): Y
Enter stock availabilty: 10
該預期的輸出應該是:
We're falling short on supply, hence we'll ship the items we have in stock right now. The remaining balance will be shipped as soon as stock arrives.
但是程式列印了這個:
Thank you for ordering from us, the items will be shipped soon.
有人可以解釋我為什么會這樣嗎??
uj5u.com熱心網友回復:
線
scanf("%s", &credit);
是錯的。
該%s格式說明需要一個指向它應該寫輸入一個字串的地址。執行此操作時,您必須確保該位置有足夠的記憶體來寫入字串。
但是,在指定的記憶體位置,只有一個字符的空間,因為與行
char credit;
你只宣告了一個字符。
為了存盤 string "Y",您至少需要兩個字符的空間,一個用于字符Y,另一個用于字串的終止空字符。在 C 中,字串的末尾總是有一個終止的空字符。
當然,可以通過為第二個字符添加空間并將匹配字符數限制為1來解決此問題,以確保有足夠的空間來存盤字串。
char credit[2];
[...]
scanf( "%1s", credit );
但是,我不推薦此解決方案。相反,我建議您使用%c格式說明符而不是%s格式說明符。該%s格式說明旨在用于整個字串,而%c格式說明旨在用于單個字符。
因此,這個解決方案可能會更好:
char credit;
[...]
scanf( "%c", &credit );
然而,這個解決方案有一個問題。上一個函式呼叫scanf
scanf( "%d", &order );
不會消耗整個前一行,但只會消耗盡可能多的字符來匹配數字。所有不屬于數字的字符,包括換行符,都將留在輸入流中。
因此,如果您呼叫
scanf( "%c", &credit );
之后,%c格式說明符可能會匹配換行符,而不是Y下一行中的 。有關此問題的更多資訊,請參閱此問題:
scanf() 將換行符留在緩沖區中
為了解決這個問題,您可以指示在嘗試匹配格式說明符之前scanf首先丟棄所有空白字符(換行符是空白字符)%c:
scanf( " %c", &credit );
解決的遺留字符問題的另一種方法是使用fgets替代scanf。該解決方案的優點是該函式的行為更加直觀,因為它通常每次函式呼叫只讀取一行輸入。與 相比scanf,它通常不會在輸入流上留下一行的剩余部分。有關更多資訊,請參閱本指南:
遠離 scanf() 的初學者指南
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379746.html
