Getting Input From Users
Lesson 10Author : Afrixi
Last Updated : November, 2022
To get input from users in C++, you can use the std::cin function. Here’s an example:
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Your age is: " << age << std::endl;
return 0;
}
In this code, the std::cin
function is used to read in an integer value entered by the user, and store it in the variable age
. The std::cout
function is used to prompt the user to enter their age, and then to output the age entered by the user.
Note that std::cin
can also be used to read in other types of values, such as floating point numbers and strings. For example, to read in a floating point number, you can do:
double height;
std::cout << "Enter your height in meters: ";
std::cin >> height;
std::cout << "Your height is: " << height << " meters" << std::endl;
To read in a string, you can use the std::getline
function, like this:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Your name is: " << name << std::endl;
return 0;
}
In this code, the std::getline
function is used to read in a string
entered by the user, and store it in the variable name
. Note that we need to include the string library to use the std::getline
function.
When using std::getline
, it’s important to note that it reads in the entire line of input, including any spaces or special characters.