C语言 C编程中的字符输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15029859/
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 05:25:06  来源:igfitidea点击:

Char input in C programming

c

提问by Tomás Francisco

I have this code:

我有这个代码:

int p3_2_4()
{
    char cargo[100];

    printf("Valor: ");
    scanf("%s", cargo);

    if (cargo == "C")
        printf("Chefe");
    else if (cargo == "o")
        printf("operario");
    else if (cargo == "i")
        printf("inspetor");
    else if (cargo == "m")
        printf("mecanico");
    else
        printf("O valor inserido nao tem correspondencia.");

    return 0;
}

I don't know how to use char type, I searched for many types of char input, but unfortunately I couldn't find my answer. I hope you can clarify me.

我不知道如何使用char类型,我搜索了很多类型的char输入,但不幸的是我找不到我的答案。我希望你能澄清我。

回答by Hunter McMillen

char[100]isn't a charit is an arrayof characters (a string). If you want to compare strings in C you can use the strcmp(a, b)or strncmp(a, b, n)functions from the string.hheader file.

char[100]不是char它是一个字符数组(一个字符串)。如果要比较 C 中的字符串,可以使用头文件中的strcmp(a, b)strncmp(a, b, n)函数string.h

char name[] = "Hunter";

if(!strcmp(name, "Hunter")) // if the return value of strcmp is 0 
{
   puts("It's me!");
}
else
{
   puts("Not me.");
}

回答by autistic

"C" isn't a char type. Proof:

“C”不是字符类型。证明:

printf("sizeof \"C\" == %zu\n", sizeof "C");
printf("sizeof (char) == %zu\n", sizeof (char));

Rather, it is a const char[2]type; "C" is a string literal. String literals translate to strings, and strings are terminated by an extra '\0'character. This explains the extra character.

相反,它是一种const char[2]类型;“C”是一个字符串文字。字符串文字转换为字符串,并且字符串以额外的'\0'字符结尾。这解释了额外的字符。

I think you want getchar()and 'C'(which are unsigned char values stored as int) rather than scanf("%s", ...)and "C", if you only intend to be using one character from the input.

如果您只想使用输入中的一个字符,我认为您想要getchar()and 'C'(它们是存储为 的无符号字符值int)而不是scanf("%s", ...)and "C"

int cargo = getchar();
if (cargo == 'C')
    puts("Chefe");
else if (cargo == 'o')
    puts("operario");
else if (cargo == 'i')
    puts("inspetor");
else if (cargo == 'm')
    puts("mecanico");
else
    puts("O valor inserido nao tem correspondencia.");

This problem seems like it'd be easy for anyone reading one of our fine books. Which book are you reading? It seems for me as though you might be ready for K&R's "The C Programming Language".

这个问题对于阅读我们一本好书的人来说似乎很容易。你在读哪本书?在我看来,您似乎已经为 K&R 的“C 编程语言”做好了准备。