转换ASCII code为一个字符值 [英] Converting ASCII code to a character value
问题描述
我刚刚开始学习如何与C程序,我试图让接受一个数字,用它作为一个ASCII值,返回与该值相关联的ASCII字符的程序。
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.
该项目工程时,参数是predefined但是当我介绍一下scanf函数功能,它编译但犯规给我同样的结果。
The program works when the parameters are predefined but when I introduce the scanf function it compiles but doesnt give me the same results.
下面是我的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.
推荐答案
您需要通过的地址敏
的到 scanf()的
(编译器应该发出此警告):
You need to pass the address of myInt
to scanf()
(the compiler should have emitted a warning for this):
scanf("%d", &myInt);
您也应该检查的返回值scanf()的
来确保敏
实际上分配到。 scanf()的
返回分配取得的数量,在这种情况下,预计将 1
:
You should also check the return value of scanf()
to ensure myInt
was actually assigned to. scanf()
returns the number of assignments made, which in this case is expected to be 1
:
if (1 == scanf("%d", &myInt))
{
}
注意 INT
比一个更大的范围内的值字符
,所以你应该检查存储在值敏
将配合的成字符
。有在头文件中定义的宏 limits.h中
,你可以用它来检查:
Note that int
has a larger range values than a char
so you should check that the value stored in myInt
will fit into a char
. There are macros defined in the header limits.h
that you can use to check:
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);
}
}
编译器应该也射出的的隐函数声明的关于问题2警告()
。要纠正,请将问题2的定义()
,或问题2的声明()
之前<$ C到$ C>的main()。
The compiler should have also emitted an implicit function declaration warning with respect to question2()
. To correct, place the definition of question2()
, or a declaration for question2()
, prior to main()
.
这篇关于转换ASCII code为一个字符值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!