In C is there a way to convert an ASCII value typed as an int into the the corresponding ASCII character as a char?
5 Answers
If i is the int, then
char c = i; makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).
2 Comments
Steve Jessop
isascii is a Posix function, not standard C. MS apparently supports it too (but deprecated), so that covers most implementations.Fred Foo
@Steve, thanks for the correction, you're right. I also misspelled
ctype.h as ctypes.h.char A; printf("ASCII value of %c = %d", c, c); In this program, the user is asked to enter a character. The character is stored in variable c. When %d format string is used, 65 (the ASCII value of A) is displayed. When %c format string is used, A itself is displayed.
Output: ASCII value of A = 65
Comments
#include <stdio.h> #include <cs50.h> int d; int main(void){ string a = get_string("enter your word: "); int i = 0; while(a[i] != '\0'){ printf("%i ", a[i]); i++; } printf("\n"); } 1 Comment
Community
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.