Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c++ - Why does adding a '0' to an int digit allow conversion to a char?

I've seen examples of this all over the place:

int i = 2;
char c = i + '0';
string s;
s += char(i + '0');

However, I have not yet seen an explanation for why adding the zero allows for the conversion.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you look at the ASCII table, asciitable, you'll see that the digits start at 48 (being '0') and go up to 57 (for '9'). So in order to get the character code for a digit, you can add that digit to the character code of '0'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...