How to take only a single character as an input in C++

Taking a single character input in C++ is

#include <iostream>

int main() {
    char input;
    std::cout << "Enter a single character: ";
    std::cin >> input;
    std::cout << "You entered: " << input << std::endl;
    return 0;
}

Output:
    Enter a single character:
a
You entered: a

 

In this code:

  1. #include <iostream>: This includes the input-output stream library.
  2. char input;: Declares a variable input of type char to store the single character input.
  3. std::cout << "Enter a single character: ";: Prompts the user to enter a character.
  4. std::cin >> input;: Takes the single character input from the user.
  5. std::cout << "You entered: " << input << std::endl;: Outputs the entered character.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top