[英]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.