C 编程如何在以下代码中正确使用 if 语句和字符串?

标签 c

#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。

reference

#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/

相关文章:

c - 当我将图中的节点数从 4 增加到大于 5 时,malloc 会导致内存损坏

c - 将节点添加到单链表无法正常工作

c - 使用 Valgrind 写入和读取错误

c - 将不同类型字符的字符串拆分为单独的字符串

c++ - 编写一个简单的 Bootloader HelloWorld - 错误函数打印字符串

c - Go:导入和 C 库之间的类型冲突

c++ - 是否有用于 double 平方根倒数的快速 C 或 C++ 标准库函数?

c - 为什么设置了 -std=c99 后 gcc 找不到 random() 接口(interface)?

c - C 中的点表示法?

c - 为什么内核在发送一定数量的字节后会强制从客户端强制发送TCP RST?