How do I print a char and its equivalent ASCII value in C?
- 1So far there seems to be no correct answer among the 12 answers. Many fail at limiting the values to the 0 to 127 range as ASCII is a 7 bit encoding, and so far none has solved the problem that the numerical value of a character in C doesn't have to be the ASCII value! The system/compiler could also be using something like EBCDIC encoding, then the numerical value of an 'a' would not be the ASCII value of an 'a' in C.BlackJack– BlackJack2017-08-17 17:01:55 +00:00Commented Aug 17, 2017 at 17:01
Add a comment |
8 Answers
This prints out all ASCII values:
int main() { int i; i=0; do { printf("%d %c \n",i,i); i++; } while(i<=255); return 0; } and this prints out the ASCII value for a given character:
int main() { int e; char ch; clrscr(); printf("\n Enter a character : "); scanf("%c",&ch); e=ch; printf("\n The ASCII value of the character is : %d",e); getch(); return 0; } 8 Comments
Pete Kirkham
Your code prints the decimal value created by converting the char to an int. This may be the ascii code on some systems, but then again it may not.
CodeCodeCode
Why the above program doesnt print ASCII characters from 127 to 160?
user007
Isn't this undefined behavior?? using
%d to print a char??Iharob Al Asimi
Sorry, -1 for
getch(). Terrible example using this non standard funcion. |
Try this:
char c = 'a'; // or whatever your character is printf("%c %d", c, c); The %c is the format string for a single character, and %d for a digit/integer. By casting the char to an integer, you'll get the ascii value.
1 Comment
David R Tribble
You don't need to cast to
int, since the standard type promotions will promote c into an int automatically.Nothing can be more simple than this
#include <stdio.h> int main() { int i; for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/ { printf("ASCII value of character %c = %d\n", i, i); } return 0; } Comments
To print all the ascii values from 0 to 255 using while loop.
#include<stdio.h> int main(void) { int a; a = 0; while (a <= 255) { printf("%d = %c\n", a, a); a++; } return 0; } 1 Comment
HeavenHM
ASCII has 7 bits so 0 to 127 after thats is system defined EASCII.
This reads a line of text from standard input and prints out the characters in the line and their ASCII codes:
#include <stdio.h> void printChars(void) { unsigned char line[80+1]; int i; // Read a text line if (fgets(line, 80, stdin) == NULL) return; // Print the line chars for (i = 0; line[i] != '\n'; i++) { int ch; ch = line[i]; printf("'%c' %3d 0x%02X\n", ch, ch, (unsigned)ch); } } 2 Comments
Nisse Engström
%X expects an unsigned int.David R Tribble
@NisseEngström - Code corrected, for the truly pedantic. Yes, it's always a good idea to use
unsigned char[] for text buffers.