Characters

Hello everyone,
Could please anyone explain to me that why should I use '0' to cast in order get the correct character display?

1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
void printCharacters() {
	for (int i = 0; i < 256; i++) {
		cout << i << "	" << static_cast<char>('0' + i) << "	" << static_cast<char>(i) << endl;
	}
}
int main (){
   printCharacters();
}
Last edited on
closed account (48T7M4Gy)
Use an ASCII table as a reference. http://www.asciitable.com/
'0' has an integer value of 48 so '0' + 48 has an integer value of 58 which if cast to a character id ASCII(58) which is the character ':'

You might be better of starting your loop at say i = 10 because some of the characters you are trying out are not printing characters.

The reason you use '0' is if you have a range of integer indices starting at zero, adding '0' enables a direct correspondence with the ASCII character from zero onwards.
Thanks!
Topic archived. No new replies allowed.