Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. It includes the necessary libraries: iostream for input/output and string for using the string data type.
  2. It defines the main function where the program starts.
  3. It declares a string variable input to hold the user's input.
  4. It prompts the user to enter a line of text.
  5. It uses std::getline(std::cin, input); to read a line of text from the user. std::getline is used instead of std::cin >> because the latter stops reading input when it encounters a space.
  6. 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).
  7. Finally, it returns 0 to indicate that the program has finished successfully.

This problem has been solved

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

1/2

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.