[英]If function not giving expected output in C
所以這是我的代碼,並且...
#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
預期的 output應該是:
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.
有人可以解釋一下為什么會這樣嗎?
線
scanf("%s", &credit);
是錯的。
%s
格式說明符需要一個指向它應該將輸入作為字符串寫入的地址的指針。 執行此操作時,您必須確保該位置有足夠的 memory 來寫入字符串。
但是,在指定的 memory 位置,只有單個字符的空間,因為與行
char credit;
你只聲明了一個字符。
要存儲字符串"Y"
,您至少需要兩個字符的空間,一個用於字符Y
,一個用於字符串的終止 null 字符。 在 C 中,字符串的末尾總是有一個終止 null 字符。
當然,可以通過為第二個字符添加空格並將匹配字符數限制為 1 來解決此問題,以確保有足夠的空間來存儲字符串。
char credit[2];
[...]
scanf( "%1s", credit );
但是,我不推薦這種解決方案。 相反,我建議您使用%c
格式說明符而不是%s
格式說明符。 %s
格式說明符適用於整個字符串,而%c
格式說明符適用於單個字符。
因此,這個解決方案可能會更好:
char credit;
[...]
scanf( "%c", credit );
然而,該解決方案存在一個問題。 前面的 function 調用scanf
scanf( "%d", &order );
不會消耗整個前一行,但只會消耗盡可能多的字符以匹配數字。 所有不屬於數字的字符,包括換行符,都將留在輸入 stream 上。
因此,如果你打電話
scanf( "%c", credit );
之后, %c
格式說明符可能會匹配換行符,而不是下一行中的Y
有關此問題的更多信息,請參閱此問題:
為了解決這個問題,您可以指示scanf
在嘗試匹配%c
格式說明符之前先丟棄所有空白字符(換行符是空白字符):
scanf( " %c", credit );
解決剩余字符問題的另一種方法是使用fgets
而不是scanf
。 此解決方案的優點是 function 的行為更直觀,因為它通常每個 function 調用僅讀取一行輸入。 與scanf
相比,它通常不會在輸入 stream 上留下一行的剩余部分。 有關詳細信息,請參閱本指南:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.