问题
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.
The program works when the parameters are predefined but when I introduce the scanf function it compiles but doesnt give me the same results.
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.
回答1:
You need to pass the address of myInt
to scanf()
(the compiler should have emitted a warning for this):
scanf("%d", &myInt);
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))
{
}
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);
}
}
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()
.
来源:https://stackoverflow.com/questions/12953665/converting-ascii-code-to-a-character-value