Sandip Kumar
Sandip Kumar

Reputation: 251

Printing ascii chart

I was trying to print complete ASCII chart . Meanwhile I saw this code on tutorialsschool.com website .

#include<stdio.h>
void main() {
int i;
for(i=0;i<=255;i++){
    printf("%d->%c\n",i,i);
}
}

It looks perfect, but the problem is that it is not printing symbols for locations (I'm using Code::Blocks IDE) such as 7,8,9,10 and 32. I am really confused why it not printing values at those locations.And it is giving some weird output on online compilers.Is it the problem of Code::Blocks. What possibly could be the other program to print these ASCII symbols.

Upvotes: 7

Views: 1750

Answers (3)

chux
chux

Reputation: 153303

Only a subset of ASCII characters are printable. Some are control characters such as line-feed, bell, etc..

Detail: ASCII is defined for codes 0 to 127. Loop only needs for(i=0;i<=127;i++) for a complete ASCII chart.

--

OTOH, perhaps one wants to print a complete chart of all char. When char are printed, they are converted to unsigned char first. So let us create a chart of all unsigned char.

Note: Using ASCII for characters code 0 to 127 in very common, but not specified by C.

To determine if the unsigned char is printable, use the isprint() function. For others, print an escape sequence.

#include<ctype.h>
#include<limits.h>
#include<stdio.h>

int main(void) {
  unsigned char i = 0;
  do {
    printf("%4d: ", i);
    if (isprint(i)) {
      printf("'%c'\n", i);
    } else {
      printf("'\\x%02X'\n", i);
    }
  } while (i++ < UCHAR_MAX);
  return 0;
}

Sample output

   0: '\x00'
   1: '\x01'
   ...
   7: '\x07'
   8: '\x08'
   9: '\x09'
  10: '\x0A'
  ...
  31: '\x1F'
  32: ' '
  33: '!'
  34: '"'
  ...
  65: 'A'
  66: 'B'
  67: 'C'
  ...
 126: '~'
 127: '\x7F'
 ...
 255: '\xFF'

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134276

You might be interested in knowing that not all the ASCII characters are printable.

For example, decimal 0 to 31 are non-printable ASCII values.

See this reference, which mentions the same.

That said, for a hosted environment, the expected signature of main() is int main(void), at least.

Upvotes: 3

tdao
tdao

Reputation: 17678

I am really confused why it not printing values at those locations.

Because those code is non-printable ASCII code. Note standard ASCII code has only 7 bit (ie 128 characters) - and several of them non-printable (control codes) - so you are not expected to be able print them (eg, can you print the Bell 0x07 ?)

http://www.asciitable.com/


And as Mohit Jain pointed out, you really need to use isprint function to check if a character is printable on standard C locale before printing it out - very handy function.

Upvotes: 6

Related Questions