How to accept a character input in C++

Overview

In this shot, we want to briefly look at how to accept a character input from a user and print the given input in C++.

How it works

The steps listed below explain how C++ accepts and return a character input from a user:

  • Step1: The program will wait for the user to enter a character value.
  • Step 2: The value entered by the user is then taken using the extraction operator, Cin, which is a standard input stream in C++. This value is taken from the user with the help of Cin method.

The Cin method in C++ is used together with the extraction operator which is written as >> and then followed by the variable where the extracted value is stored.

Syntax

char name;
cin>>name;
  • Step 4: from the code above, the first statement char name decalares the variable of type char (which stands for character) we called name while the second, cin>>name, extracts a value to be stored in it from Cin.

  • Step 5: Cout output stream is then used to print out the value the user entered.

Syntax

Cout<< "Hi,"<<name<<"endl;

From the above, statement, the cout method simply helps to print the value of the integer passed to the name variable by the user.

This is the last step in this program because the user input is now read and printed.

Example: A simple program that reads character input

#include<iostream>
using namespace std;
int main()
{
// creating the character variables
char  first, last;

// sending an output character to the user
cout<<"Enter your Initials:"<<endl;

// getting an input from a user
cout<<"\tYour First name initial:";

// storing the input made in line 11
cin>>first;

// getting an input from a user
cout<<"\tYour last name initial:";

// storing the input made in line 17
cin>>last;

// printing the characters provided by the user
cout<<"Hello, "<<first<<","<<last<<endl;

return 0; 
}

Output

Enter your Initials:
	Your First name initial:T
	Your last name initial:C
	Hello, T,C

Free Resources