cpp / beginner
Snippet
Reading User Input with std::cin
std::cin reads input from the keyboard. The >> operator extracts data from the input stream and stores it in the variable. It automatically handles type conversion for built-in types. The program pauses at std::cin until the user enters data and presses Enter.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>#include <string>int main() {std::string name;int age;std::cout << "Enter your name: ";std::cin >> name;std::cout << "Enter your age: ";std::cin >> age;std::cout << "Hello " << name << ", you are " << age << " years old." << std::endl;return 0;}
Breakdown
1
std::cin >> name
Reads a word from input and stores it in name variable
2
std::cin >> age
Reads an integer from input, automatic type conversion
3
std::cout << "Enter your name: "
Prompts the user before waiting for input
4
>>
Extraction operator: pulls data from std::cin into variable