Taha Ali
Taha Ali

Reputation: 1324

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 --> e.g:

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

this will output "66" on the console.

How can this be done in C++ ??

Upvotes: 0

Views: 8602

Answers (5)

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 1

1''
1''

Reputation: 27125

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

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

Upvotes: 2

Pete Becker
Pete Becker

Reputation: 76498

No cast needed:

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

Upvotes: 4

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

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).

Upvotes: 4

Carl Norum
Carl Norum

Reputation: 225202

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);

Upvotes: 4

Related Questions