Joined: Sun May 25, 2008 5:34 pm Posts: 95 Has thanked: 2 time Have thanks: 1 time
Code:
/* * This program prints out a table of the ascii character values. */ #include <stdio.h> #include <ctype.h>
int main() { int code; /* Ascii value. */
for(code = 0; code < 128; ++code) { /* Print the code and the character itself. */ printf("%3d ", code); if(isspace(code)) printf(" "); else if(isprint(code)) printf("%c", code); else printf(" ");
/* If any of the interesting categories match, print it. */ if(code == '\n') printf(" (newline, \\n)\n"); else if(code == ' ') printf(" (space)\n"); else if(code == '\t') printf(" (tab, \\t)\n"); else if(isspace(code)) printf(" (blank character)\n"); else if(iscntrl(code)) printf(" (control character)\n"); else if(isupper(code)) printf(" (capitol of %c)\n", tolower(code)); else if(islower(code)) printf(" (lower case of %c)\n", toupper(code)); else if(isdigit(code)) printf(" (digit)\n", toupper(code)); else putchar('\n'); } }
In the first printf, the construct %3d is the same as %d, except that printf is instructed to use at least three spaces to represent the number, padding with spaces at the left if necessary. (Use %-3d if you want the padding on the right.) This just keeps the output nicely aligned.
Notice how the integer value code is printed both with %d to get the integer value, and with %c to get the character itself. This works equally well if the variable is declared as char: it can be printed with either %d or %c.