Reputation: 1324
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: 8584
Reputation: 234685
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
Reputation: 27095
It can be done the exact same way in C++:
{
char ch='A';
ch++;
printf("%d",ch);
}
Upvotes: 2
Reputation: 76245
No cast needed:
{
char ch='A';
ch++;
std::cout << ch << ": " << +ch << '\n';
}
Upvotes: 4
Reputation: 110658
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
Reputation: 224864
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