简体   繁体   中英

Can ASCII code for a char be printed in C++ like in C?

As we can print the ASCII code and increment it in C --> eg:

{
char ch='A';
ch++;
printf("%d",ch); 
}

this will output "66" on the console.

How can this be done in C++ ??

printf will work just like that in C++. But if you want to use cout , you just need to cast:

char ch = 'A';
ch++;
std::cout << static_cast<int>(ch);

Yes, just cast it to an int before you output it, so that it isn't interpreted as a character:

char ch = 'A';
ch++;
std::cout << static_cast<int>(ch);

Note, however, that this isn't guaranteed to output the value corresponding to the character 'B' . If your execution character set is ASCII or some other sane character set, then it will be, but there is no guarantee from the standard about your execution character set (other than the numerical digit characters, 0 to 9 , having consecutive values).

No cast needed:

{
char ch='A';
ch++;
std::cout << ch << ": " << +ch << '\n';
}

It can be done the exact same way in C++:

{
char ch='A';
ch++;
printf("%d",ch); 
}

Accepting the fact that neither C nor C++ insist on the encoding being ASCII (although it's ubiquitous on desktop computers), the code you present is valid C++.

In many (although by no means all) respects, C++ is a superset of C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM