how do i write a c++ program that prints the integer equivalent of a character typed at the keyboard.?
(Integer Equivalent of a Character) Here is a peek ahead. In this chapter you learned about integers and the type int. C++ can also represent uppercase letters, lowercase letters and a considerable variety of special symbols. C++ uses small integers internally to represent each different character. The set of characters a computer uses and the corresponding integer representations for those characters are called that computer's character set. You can print a character by enclosing that character in single quotes, as with
cout << 'A'; // print an uppercase A
You can print the integer equivalent of a character using static_cast as follows:
cout << static_cast< int >( 'A' ); // print 'A' as an integer
This is called a cast operation (we formally introduce casts in Chapter 4). When the preceding statement executes, it prints the value 65 (on systems that use the ASCII character set). Write a program that prints the integer equivalent of a character typed at the keyboard. Store the input in a variable of type char. Test your program several times using uppercase letters, lowercase letters, digits and special characters (like $).
- ?Lv 79 years agoFavorite Answer
While static_cast is the most appropriate solution, for added variety, you can use the under-appreciated C++ operator "unary plus". I wonder how many textbooks even care to explain what it does.
std::cout << "Enter a character: ";
std::cin >> x;
std::cout << "The ASCII value of " << x << " is " << +x << '\n';
- 9 years ago
It's very easy Question ... and also very easy Answer
char x = 'A';
Have Fun with Programming Language :)
- Don't sue me!Lv 59 years ago
You don't always need to type static_cast.
You could use the C-style cast instead:
cout << (int)'A';
- 7 years ago
Another way you can do is :
cout<<"Enter any key"<<endl;
cout<<"Corresponding ascii is "<<d;