Write a program test-ascii.cpp that asks the user to input a line of text (which may possibly include spaces). The program should report all characters from the input line together with their ASCII codes.
Question
Write a program test-ascii.cpp that asks the user to input a line of text (which may possibly include spaces). The program should report all characters from the input line together with their ASCII codes.
Solution
Sure, here is a simple C++ program that does what you asked for:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Please enter a line of text: ";
std::getline(std::cin, input);
for (char c : input) {
std::cout << "Character: " << c << ", ASCII code: " << static_cast<int>(c) << std::endl;
}
return 0;
}
Here's how this program works:
- It includes the necessary libraries: iostream for input/output and string for using the string data type.
- It defines the main function where the program starts.
- It declares a string variable
inputto hold the user's input. - It prompts the user to enter a line of text.
- It uses
std::getline(std::cin, input);to read a line of text from the user.std::getlineis used instead ofstd::cin >>because the latter stops reading input when it encounters a space. - It then loops over each character in the input string. For each character, it prints the character itself and its ASCII code. The ASCII code is obtained by casting the character to an integer using
static_cast<int>(c). - Finally, it returns 0 to indicate that the program has finished successfully.
Similar Questions
Write a C program to input any two characters and a number (number of lines) from thekeyboarddisplayatriangleasshowninbelowfigure.Thetwocharactersshouldfillthetrianglein every other place
Write a C program to read a sentence through keyboard and to display the count ofwhite spaces in the given sentence.
Program to count characters spaces lines in file content
How can you read a string with spaces using scanf?Marks : 1Negative Marks : 0Answer herescanf("%s", str);scanf("[^\n]", str);scanf(" %[^\n]", str);scanf("%[ ]", str);
Write a program that prints the ASCII alphabet, in lowercase, not followed by a new line.You can only use one print function with string formatYou can only use one loop in your codeYou are not allowed to store characters in a variableYou are not allowed to import any module
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.