cpp / beginner
Snippet
Getting User Input
std::cin reads input from the keyboard. The >> operator extracts data from the input stream and stores it in the variable. It pauses program execution until the user types and presses Enter. Use >> for simple space-separated input.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>#include <string>int main() {std::cout << "Enter your name: ";std::string name;std::cin >> name;std::cout << "Hello, " << name << "!" << std::endl;std::cout << "Enter your age: ";int age;std::cin >> age;std::cout << "You are " << age << " years old." << std::endl;return 0;}
Breakdown
1
std::cin >> name;
Reads a word from keyboard input and stores it in the string variable name
2
std::cin >> age;
Reads an integer from keyboard input and stores it in the int variable age