#include <stdio.h>
int main()
{
char apple[]="Apple";
char banana[]="Banana";
char orange[]="Orange";
printf("Choose one of the below options\n\n");
printf("Which fruit do you like the most: Apple, Banana, Orange\n\n");
scanf("%s",&apple,&banana,&orange);
if("%s", apple)
{
printf("You chose Apple.\n");
}
if("%s",banana)
{
printf("You chose banana.\n");
}
}
//我希望代码能够简单地在屏幕上打印我选择的选择。但是当我运行代码时,它会打印 Apple 和 Banana。如果我输入 Apple,我不希望它打印 Banana。我需要使用 else 语句吗?或者我还缺少什么?谢谢,我对 C 编程很陌生。
最佳答案
您需要使用 strcmp() 来比较字符串。请参阅以下代码。
如果两个字符串的内容相等,strcmp() 将返回 0。
如果第一个不匹配的字符在 ptr1 中的值低于 ptr2 中的值,strcmp() 将返回 <0。
如果第一个不匹配的字符在 ptr1 中的值大于 ptr2 中的值,则 strcmp() 将返回 >0。
#include <stdio.h>
#include <string.h>
int main()
{
char apple[]="Apple";
char banana[]="Banana";
char orange[]="Orange";
char input[100];
printf("Choose one of the below options\n\n");
printf("Which fruit do you like the most: Apple, Banana, Orange\n\n");
scanf("%s",input);
if(strcmp(input,apple)==0)
{
printf("You chose Apple.\n");
}
if(strcmp(input,banana)==0)
{
printf("You chose banana.\n");
}
if(strcmp(input,orange)==0)
{
printf("You chose orange.\n");
}
return 0;
}
关于C 编程如何在以下代码中正确使用 if 语句和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037873/