capypad
0 day streak
cpp / beginner
Snippet

Reading User Input with cin

The cin object reads user input from the keyboard. Use >> (stream extraction) for simple types like int and double. For strings with spaces, use std::getline() which reads an entire line until the Enter key is pressed.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
 
int main() {
std::string name;
int age;
double height;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Enter your height in meters: ";
std::cin >> height;
std::cout << "\nHello, " << name << "!" << std::endl;
std::cout << "You are " << age << " years old." << std::endl;
std::cout << "You are " << height << "m tall." << std::endl;
return 0;
}
Breakdown
1
std::getline(std::cin, name)
Reads an entire line of text including spaces into the string
2
std::cin >> age;
Extracts an integer from input (stops at whitespace)
3
std::cin >> height;
Extracts a double from input for decimal numbers