C++ User Input
User input is data that a person types while a program runs. The std::cin stream reads that typed data into variables.
Reading one word
The prompt prints first, with no new line after it. std::cin then stores the typed word in name.
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << std::endl;
return 0;
}Reading two numbers
One std::cin line reads two numbers here. Each number lands in its own variable, in order.
#include <iostream>
#include <string>
int main() {
int a;
int b;
std::cout << "Enter two numbers: ";
std::cin >> a >> b;
std::cout << "Sum: " << a + b << std::endl;
return 0;
}Reading a word and a number
std::cin fills the variables in the order listed. The word lands in name and the number lands in age.
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Name and age: ";
std::cin >> name >> age;
std::cout << name << " is " << age << std::endl;
return 0;
}Example
#include <iostream>
#include <string>
int main() {
std::string item;
int quantity;
std::cout << "Item and quantity: ";
std::cin >> item >> quantity;
std::cout << "Order: " << quantity << " x " << item << std::endl;
return 0;
}Key points
- A prompt is a short message printed before input is read.
- Use std::cin to read typed values into variables.
- The >> signs send each typed value into its variable.
- std::cin reads values in order, split by spaces.
- One std::cin line can fill two variables in order.
- Use std::getline to read a whole line, spaces included.
In this example, the prompt prints with no new line after it. std::cin stores the first typed word in item. std::cin stores the number after it in quantity. The last print builds one line from both values.
Note
A prompt printed without std::endl stays on the same line as the next output.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
Which line reads a typed word into a variable named name?