C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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

Print character through ASCII value using cout in C++

By: IncludeHelp, on 13 FEB 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.







COMMENTS