Lesson 5 · 5 of 20
Reading from the keyboard · C++
Ask the user for data in C++ with std::cin and >> for numbers and words, and with std::getline for whole lines with spaces.

`std::cin` is the keyboard input, the partner of std::cout. With `>>` it reads one word and converts it to the variable's type: std::cin >> tickets stores an int and std::cin >> price a double.
>> stops at the first space, so for a full name you use `std::getline(std::cin, name)`, which reads the whole line, spaces included.
In this example the answers come from the input.txt file, as if someone were typing them, so they do not appear in the output: you see each question and, on the next line, the program's reply. In the DMarlon Studio console (F9) you can type them yourself.
Be careful when mixing the two: after std::cin >> price, the Enter at the end of that line is still waiting, and a getline would read an empty line. `std::cin >> std::ws` skips any pending spaces and line breaks before reading the film title.
>> can be chained too: std::cin >> row >> seat reads two numbers typed on the same line, separated by a space.
Code · main.cpp
#include <iostream>#include <string>int main() { std::string name; std::cout << "What is your name? "; // getline reads the whole line, spaces included. std::getline(std::cin, name); std::cout << "\nHello, " << name << "!\n"; int tickets; double price; std::cout << "How many tickets? "; // >> reads one word and converts it to the type of the variable. std::cin >> tickets; std::cout << "\nPrice per ticket? "; std::cin >> price; std::cout << "\n" << tickets << " tickets cost " << tickets * price << " euros\n"; // After >>, the Enter key is still waiting: std::ws skips it. std::string film; std::cout << "Which film? "; std::getline(std::cin >> std::ws, film); std::cout << "\nEnjoy " << film << ", " << name << "!\n"; // Several values on one line: >> skips the spaces between them. int row, seat; std::cout << "Row and seat? "; std::cin >> row >> seat; std::cout << "\nYour seat: row " << row << ", seat " << seat << '\n'; return 0;}Input (what gets typed) · input.txt
Ana Garcia 3 8.50 The Lord of the Rings 7 12
Output · c++ -std=c++17 main.cpp -o main && ./main
What is your name? Hello, Ana Garcia! How many tickets? Price per ticket? 3 tickets cost 25.5 euros Which film? Enjoy The Lord of the Rings, Ana Garcia! Row and seat? Your seat: row 7, seat 12
Key points
std::cin >> xreads one word and converts it to the type ofx.std::getline(std::cin, s)reads a whole line.- After
>>, usestd::cin >> std::wsbeforegetline. std::cin >> a >> breads several values in a row.
Exercise
Also ask how many tubs of popcorn they want (4.50 euros each) and print the total for tickets and popcorn. Add the answer to the end of input.txt.