How to Receive Input From a User in C++
In this article, we show how to receive input from a user in C++.
Not every program in C++ is just you as a programmer outputting data to a screen.
Many times, we'll want to receive input from a user.
So how do we receive input from a user in C++?
We use the cin function.
Just as we output data to a user using the cout function, we receive input from a user using the cin function.
However, unlike a cout function, which uses <<, the cin function has the symbols going to the opposite side, >>.
We will show 2 programs of us getting input from a user, first a string and then a number.
Receiving a String From a User
A string is a group of characters joined together that can be comprised of letters, numbers, and other combination of characters.
A string can be any characters such as a color like "blue", "orange", "brown", etc.
In the program below we will ask the user for his or her favorite color.
So in order to output data to a user or get
input data from a user, you need the iostream library. This is
obtained through the line, #include In order to use strings in C++, you must include
the string library. This is obtained through the line,
#include We then use the line, using namespace std;, so that
we don't have to use std:: throughout the code.
We then have our main() function, which is where
our program begins.
We create a string, favoritecolor.
We then ask the user what is his/her favorite color.
With the line, cin >> favoritecolor;, we are able to save
the input that the user enters into the string variable, favorite color.
We then output the favoritecolor variable that has saved
the user's favorite color.
We now show how to receive a number (in this case, specifically
an integer) from a user.
This is shown below.
So this program is very similar to the first with the exception
that the user we are looking for now is an integer, not a string.
Therefore, we declare a int, favoritenumber.
We then save this number that the user enters into the
int variable, favoritenumber.
And this is how to receive input from a user in C++.
Related Resources
How to Write Contents to a File in C++
Receiving a Number From a User
How to Append Contents to a File in C++