tags:

views:

347

answers:

4

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
mobrule
Stephen Canon
Ok, great, thanks!
Chris_45
@stephen: thanks for the errata! fixed!
ennuikiller
Your do-loop never terminates; you need to add an i++. Better yet, use a for-loop, because it's clearer.
Loadmaster
Loadmaster
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
Ugh! Where's the indentation? ...my eyes, my eyes... O_o
Gary Willoughby
Ampersand missing from your scanf()
Ashwin
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
+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
You don't need to cast to `int`, since the standard type promotions will promote `c` into an `int` automatically.
Loadmaster
Whoops - thanks for the catch. Was probably just trying to be too explicit :)
MBillock
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
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