c - C 中的 If 语句输出无效

标签 c string if-statement compare string-comparison

<分区>

我正在学习 C 编程语言,我正在尝试做一个 If 语句,如果用户在其中输入“hey”,则读取 var is hey,否则读取,则 var is not hey,但是,在执行时,即使输入嘿,它也会显示,var 不是嘿,我该如何解决这个问题?

#include <stdio.h>
void main(void){
        char var[3];
        printf("Enter your name: ");
        scanf("%s", &var);
        printf("%s", &var);
        printf("\n");
        if(var == "hey"){
                printf("The var is hey");
        }
        if(var != "hey"){
                printf("The var is not hey");
        }
        printf("\n");
        }

最佳答案

使用strcmp()比较字符串 n C,像这样:

if(strcmp(var, "hey") == 0) {
    printf("The var is hey");
}
else {
    printf("The var is not hey");
}

PS:我们通常写int main(void) {}。在 What should main() return in C and C++? 中阅读更多内容

关于c - C 中的 If 语句输出无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610436/

相关文章:

c - 在控制台上显示

algorithm - "spacify"CamelCased 字符串的算法

java - 负字符串长度

ios - 如何防止在暂停场景(取消暂停后)上运行 SKAction,节点纹理在暂停/取消暂停场景后不会改变

javascript - 绑定(bind)onclick事件

if-statement - 如何在 VBScript for Classic-ASP 中执行单行 If 语句?

c - 为什么 C 标准不支持嵌套函数?

c - libnet.h 没有那个文件或目录

java - 在 .c 和 .cpp 文件 (JNI) 中声明的文件范围变量的生命周期是否有保证?

android - 在android中只获取字符串的一部分?