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++.
The steps listed below explain how C++ accepts and return a character input from a user:
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.
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.
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.
#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;
}
Enter your Initials:
Your First name initial:T
Your last name initial:C
Hello, T,C