c sharp Logo

User Input


To get user input in C++, you can use the std::cin object. The std::cin object is a stream object that represents the standard input stream.

To read user input from the std::cin object, you can use the extraction operator (>>). The extraction operator extracts data from a stream and stores it in a variable.

For example, the following code reads an integer value from the user and stores it in the variable age:

int age;

std::cin >> age;

 

The user can then enter an integer value and press Enter. The std::cin object will read the user input and store it in the variable age.

You can also use the std::getline() function to read a line of text from the user. The std::getline() function extracts data from a stream up to a delimiter character (such as a newline character) and stores it in a string variable.

For example, the following code reads a line of text from the user and stores it in the variable name:

std::string name;

std::getline(std::cin, name);

 

The user can then enter their name and press Enter. The std::getline() function will read the user input up to the newline character and store it in the variable name.

Once you have read the user input, you can use it in your code. For example, you could use it to calculate a value, print a message to the console, or store it in a database.

Example

The following example shows how to get user input in C++:

#include <iostream>

 

int main() {

  // Declare two variables.

  int age;

  std::string name;

 

  // Get the user's age.

  std::cout << "Enter your age: ";

  std::cin >> age;

 

  // Get the user's name.

  std::cout << "Enter your name: ";

  std::getline(std::cin, name);

 

  // Print a message to the console.

  std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;

 

  return 0;

}

 

Output:

Enter your age: 25

Enter your name: John Doe

Hello, John Doe! You are 25 years old.