How do I print a char and its equivalent ASCII value in C?
+6
A:
This prints out all acsii values
void main()
{
int i;
i=0;
do
{
printf("%d %c \n",i,i);
i++;
}
while(i<=255);
}
and this prints out the acsii value for a given character:
void 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();
}
ennuikiller
2009-09-24 15:54:45
mobrule
2009-09-24 15:59:00
Stephen Canon
2009-09-24 15:59:18
Ok, great, thanks!
Chris_45
2009-09-24 16:04:30
@stephen: thanks for the errata! fixed!
ennuikiller
2009-09-24 16:07:33
Your do-loop never terminates; you need to add an i++. Better yet, use a for-loop, because it's clearer.
Loadmaster
2009-09-24 16:10:44
Loadmaster
2009-09-24 16:11:43
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.
Pete Kirkham
2009-09-24 16:24:55
Ugh! Where's the indentation? ...my eyes, my eyes... O_o
Gary Willoughby
2009-09-24 17:20:04
Ampersand missing from your scanf()
Ashwin
2009-09-24 17:22:37
oh man, give me a break! This isn't production code. It's meant more like pseudocode, but @loadmaster's point is a good one! dont know how I forgot that!
ennuikiller
2009-09-24 17:40:48
+1
A:
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.
MBillock
2009-09-24 15:57:21
You don't need to cast to `int`, since the standard type promotions will promote `c` into an `int` automatically.
Loadmaster
2009-09-24 16:18:13
Whoops - thanks for the catch. Was probably just trying to be too explicit :)
MBillock
2009-09-24 17:10:28
A:
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)
{
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, ch);
}
}
Loadmaster
2009-09-24 16:16:49
A:
This should work in any C system, not only those which are ASCII or UTF-8 based:
printf ( " Q is decimal 81 in ASCII\n" );
You did ask for a char; the other 96 of them are left as an exercise for the reader.
Pete Kirkham
2009-09-24 16:20:19