如何比较字符? [英] How to compare a char?

查看:17
本文介绍了如何比较字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 c.我有个问题.为什么我的程序不起作用?

I am learning c. I have a question. Why doesn't my program work?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

char cmd;

void exec()
{
        if (cmd == "e")
        {
                printf("%c", cmd);
                // exit(0);
        }
        else
        {
                printf("Illegal Arg");
        }
}

void input()
{
        scanf("%c", &cmd);
        exec();
}

int main()
{
        input();
        return 0;
}

我插入了一个e",但它表示非法参数.
cmd 不等于e".为什么?我用 scanf 将 cmd 设置为e".

I insert a "e" but it says illegal arg.
cmd is not equal to "e". Why? I set cmd with scanf to "e".

推荐答案

首先,在 C 中单引号是字符字面量,双引号是字符串字面量.因此,C"和C"不是一回事.

First of, in C single quotes are char literals, and double quotes are string literals. Thus, 'C' and "C" are not the same thing.

要进行字符串比较,请使用 strcmp.

To do string comparisons, use strcmp.

const char* str = "abc";
if (strcmp ("abc", str) == 0) {
   printf("strings match
");
}

要进行字符比较,请使用相等运算符.

To do char comparisons, use the equality operator.

char c = 'a';
if ('a' == c) {
   printf("characters match
");
}

这篇关于如何比较字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆