C语言 将 ASCII 码转换为字符值

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

Converting ASCII code to a character value

ccharacterascii

提问by alexeidebono

I've just started learning how to program in C and I'm trying to make a program that accepts a number and uses it as an ASCII value to return the ASCII character associated with that value.

我刚刚开始学习如何用 C 编程,我正在尝试制作一个接受数字并将其用作 ASCII 值的程序,以返回与该值关联的 ASCII 字符。

The program works when the parameters are predefined but when I introduce the scanf function it compiles but doesnt give me the same results.

该程序在参数预定义时工作,但是当我引入 scanf 函数时,它会编译但不会给我相同的结果。

Here is my code :

这是我的代码:

#include <stdio.h>

int main(void) 
{
    question2();
    return 0; 
}

int question2(void)
{


    int myInt = 65;

    scanf("%d", myInt);
    char ch = myInt;

    printf("%c",ch);

    return 0;
}

Cheers and thanks for any help guys.

干杯和感谢任何帮助家伙。

回答by hmjd

You need to pass the addressof myIntto scanf()(the compiler should have emitted a warning for this):

你需要通过地址myIntscanf()(编译器应该发出此警告):

scanf("%d", &myInt);

You should also check the return value of scanf()to ensure myIntwas actually assigned to. scanf()returns the number of assignments made, which in this case is expected to be 1:

您还应该检查 的返回值scanf()以确保myInt实际分配给。scanf()返回所做的分配数量,在这种情况下预计为1

if (1 == scanf("%d", &myInt))
{
}

Note that inthas a larger range values than a charso you should check that the value stored in myIntwill fitinto a char. There are macros defined in the header limits.hthat you can use to check:

请注意,int具有比 a 更大的范围值,char因此您应该检查存储在中的值myInt是否适合a char。标头limits.h中定义了宏,可用于检查:

if (1 == scanf("%d", &myInt))
{
    if (myInt >= CHAR_MIN && myInt <= CHAR_MAX)
    {
        printf("%c\n", (char) myInt);
    }
    else
    {
        printf("%d out-of-range: min=%d, max=%d\n",
            myInt, CHAR_MIN, CHAR_MAX);
    }
}

The compiler should have also emitted an implicit function declarationwarning with respect to question2(). To correct, place the definition of question2(), or a declaration for question2(), prior to main().

编译器还应该发出关于 的隐式函数声明警告question2()。要更正,请将 的定义question2()或声明放在question2()之前main()