Display ASCII Values

Display ASCII Values

Make a program that uses getline to get user input and place it in a string.

Loop the characters in the string, and for each character, output the character along with their ASCII code of the character before going to a new line.

Example

ENTRY
E - 69
N - 78
T - 84
R - 82
Y - 89

Hint

You have to include <iostream> and <string>.

Use getline to avoid running into problems getting inputs with spaces.

You can use the range-based loop to cycle through each char in the std::string.

Answer

#include <iostream>
#include <string>

int main() {
    // Use getline to get user input
    std::cout << "Enter a string: ";
    std::string input;
    std::getline(std::cin, input);

    // Loop through each character in the string
    for (char ch : userInput) {
        // Output the character and its ASCII value
        std::cout << ch << " - " << int(ch) << std::endl;
    }
}

This program loops each character of the string using a range-based loop.

For each character the char as well as the char cast to an int is output. Casting a char to an int like this will give you the ASCII code of the character.

Questions