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

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

问题描述

我正在学习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中,单引号是char文字,而双引号是字符串文字.因此,"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\n");
}

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

To do char comparisons, use the equality operator.

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

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

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