Home » Programming Tips & Tricks » C++ - Tips & Tricks

Print character through ASCII value using cout in C++



Here, we are going to learn how can we print the character using given ASCII code in C++ programming language using cout? And here is a C++ program that will also print the all characters with their ASCII codes.
Submitted by IncludeHelp, on February 13, 2017

Generally, when we pass an integer value to cout, it prints value in decimal format and if we want to print a character using ASCII value (which is stored in a variable), cout will not print the character normally.

Consider the example:

#include <iostream>
using namespace std;

int main()
{
	int var=65;
	cout<<var<<endl;
	return 0;
}

Here, output will be 65.

Then, how to print character?

We can use cast type here, by casting into char we are able to get result in character format. We can use cout<<char(65) or cout<<char(var), that will print 'A'. (65 is the ASCII value of 'A').

Consider the example:

#include <iostream>
using namespace std;

int main()
{
	int var=65;
	cout<<(char)var<<endl;
	return 0;
}

Here, output will be A.



Printing ASCII codes from A to Z

#include <iostream>
using namespace std;

int main()
{
	//loop counter
	int i;
	
	for(i='A'; i<='Z'; i++)
		cout<<"CHAR: "<<(char)i<<" ASCII: "<<i<<endl;
	
	return 0;
}

Output

CHAR: A ASCII: 65
CHAR: B ASCII: 66
CHAR: C ASCII: 67
CHAR: D ASCII: 68
CHAR: E ASCII: 69
CHAR: F ASCII: 70
CHAR: G ASCII: 71
CHAR: H ASCII: 72
CHAR: I ASCII: 73
CHAR: J ASCII: 74
CHAR: K ASCII: 75
CHAR: L ASCII: 76
CHAR: M ASCII: 77
CHAR: N ASCII: 78
CHAR: O ASCII: 79
CHAR: P ASCII: 80
CHAR: Q ASCII: 81
CHAR: R ASCII: 82
CHAR: S ASCII: 83
CHAR: T ASCII: 84
CHAR: U ASCII: 85
CHAR: V ASCII: 86
CHAR: W ASCII: 87
CHAR: X ASCII: 88
CHAR: Y ASCII: 89
CHAR: Z ASCII: 90





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.