C语言 C - 比较两个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17026372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:39:19  来源:igfitidea点击:

C - Comparing two characters

ccomparecharacter

提问by tenkii

I am having trouble comparing two characters. I've written a very basic C problem to try out command line arguments.

我在比较两个字符时遇到问题。我写了一个非常基本的 C 问题来尝试命令行参数。

Here is my code so far:

到目前为止,这是我的代码:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    char ch;
    char *type = "";
    char *gender = "";
    int baby = 0;
    int count = 0;

    /* Options:
     * -t = type of pet
     * -g = gender
     * -b = baby or adult
     */
    while ((ch = getopt(argc, argv, "t:g:b")) != EOF)
        switch (ch) {
            case 't':
                type = optarg;
                break;
            case 'g':
                gender = optarg;
                break;
            case 'b':
                baby = 1;
                break;
            default:
                fprintf(stderr, "Invalid option.\n");
                return 1;
        }

    argc -= optind;
    argv += optind;

    printf("You have chosen a %s.\n", type);
    if (gender == 'f')
        puts("It's a girl");
    if (gender == 'b')
        puts("It's a boy.");

    // The main command line arguments should be about the traits of the pet
    printf("%s", "Traits: ");
    for (count = 0; count < argc; count++)
        printf("%s ", argv[count]);

    return 0;
}

So if I type this into the terminal:

所以如果我在终端中输入:

  $ ./pet_shop -t dog -g f cute small

I get this as output:

我得到这个作为输出:

  You have chosen a dog:
  Traits: cute small

The output it missing information about the gender, it should be a girl since I entered f. But I tried checking by printf("%i", gender) which gave the value 0. Is g == 'f' the incorrect way of comparing two characters?

输出它缺少关于性别的信息,它应该是一个女孩,因为我输入了 f。但是我尝试通过 printf("%i", sex) 检查它的值为 0。g == 'f' 是比较两个字符的不正确方法吗?

回答by Fred Foo

genderis a char*, i.e. a pointer to a string's first charadcter. When you compare that to a single char, both the charand the pointer are converted to integers and an integer comparison is done.

gender是 a char*,即指向字符串第一个字符的指针。当您将其与单个 进行比较时,charthechar和指针都将转换为整数并完成整数比较。

To compare strings, use strcmpfrom <string.h>:

要比较字符串,请使用strcmpfrom <string.h>

if (strcmp(gender, "f") == 0)
    // it's a girl

Note the double quote (") which signifies a string, rather than a single character.

请注意"表示字符串而不是单个字符的双引号 ( )。

回答by slugonamission

The problem is that you're comparing a string (or rather, a char*) to a char. This comparison (i.e. if(gender == 'f')) will compare the raw pointer value to the character instead of comparing the contents of the string to the character. Instead, you need to dereference the pointer and then compare that value, or index into the string, i.e. if(gender[0] == 'f').

问题在于您将字符串(或者更确切地说, a char*)与 a 进行比较char。这种比较(即if(gender == 'f'))将原始指针值与字符进行比较,而不是将字符串的内容与字符进行比较。相反,您需要取消引用指针,然后比较该值,或索引到字符串中,即if(gender[0] == 'f').

Of course, it would also be a good idea to check that the string actually contains something before attempting that in order to avoid a segfault.

当然,在尝试之前检查字符串是否确实包含某些内容也是一个好主意,以避免出现段错误。

回答by Shahbaz

You have:

你有:

char *gender = "";

So genderis a string, not a character. To compare strings, use strcmp.

gender字符串也是如此,而不是字符。要比较字符串,请使用strcmp.

回答by abelenky

You first declared gender as a string:

您首先将性别声明为字符串:

char *gender = "";

Then you later treat is as a single character:

然后您稍后将 is 视为单个字符:

if(gender == 'f')
   [...]
if(gender == 'b')

You need to clarify in your own mind what genderis, before you try and code it.
Pick one definition, and stick with it.

gender在尝试编写代码之前,您需要在自己的脑海中弄清楚是什么。
选择一个定义,并坚持下去。