So far every value was written into the program. A useful program asks the person running it for information and responds to what they type. The person running a program is called its user, and what they give the program is its input.
std::getline reads one line
std::cin is the keyboard, as std::cout is the screen. The name is short for "character input". This program asks a question, reads the line the user types and uses it:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}If the user types Ada and presses Enter, the whole conversation on the screen looks like this:
What is your name? Ada
Hello, Ada!Line by line:
std::string name;defines a string variable to put the answer in. Astd::stringdefined with no first value starts as empty text, so this is safe. (Numbers get no such favour: always give anintor adoublea first value.)- The next line prints a question. A message that tells the user what to type is called a prompt. It ends with a space and has no
\n, so that the user's typing appears on the same line, a little after the question mark. std::getline(std::cin, name);waits until the user has typed a line and pressed Enter, then stores that line inname.
std::getline is a function: a named action that is already written for you. Writing its name followed by round brackets calls the function, which means "do that action now". The values between the brackets are its arguments: the things the function works with. Here there are two, separated by a comma: where to read from (std::cin) and which variable to fill (name).
Running programs that read input
This example has no Edit & run button, because a button cannot stop and wait for you to type. Run it in the C++ playground instead:
- Copy the program into the editor.
- Open Standard input below the output and type what the user would type, one answer per line. For this program, type
Ada. - Press Run.
"Standard input" is the name programmers use for the stream of text that a program reads, which is normally the keyboard. On this site the program runs on our server, so you provide the typed lines in advance. Because nobody presses Enter on the screen there, the typed line is not shown in the output, and the reply follows the prompt on the same line: What is your name? Hello, Ada!. The program has still read Ada exactly as it would from a keyboard.
On your own computer the program behaves exactly as the conversation above shows: it stops at std::getline and waits for you.
Typed digits are text, not a number
What the user types arrives as characters. std::getline stores them in a string, even when they are digits. That matters as soon as you calculate.
#include <iostream>
#include <string>
int main() {
std::string answer = "36"; // stands in for what the user typed
std::cout << answer + answer << '\n';
}This prints 3636. Between strings, + joins. The string "36" is two characters, a 3 and a 6. It is not the number thirty-six.
The function std::stoi (short for "string to integer") takes a string of digits and gives back the int it spells. std::stod ("string to double") does the same for a number with a decimal point. Both come with #include <string>. Changing a value from one type to another is called converting it.
#include <iostream>
#include <string>
int main() {
std::string answer = "36";
int age = std::stoi(answer);
std::cout << age + age << '\n';
std::cout << std::stod("2.5") * 2 << '\n';
}This prints 72 and 5.
Here is a complete program that reads a line, converts it and calculates:
#include <iostream>
#include <string>
int main() {
std::string answer;
std::cout << "How old are you? ";
std::getline(std::cin, answer);
int age = std::stoi(answer);
int next_year = age + 1;
std::cout << "Next year you will be " << next_year << ".\n";
}std::getline stores them as the string "36". std::stoi converts that to the int 36, and only then does + 1 mean arithmetic.std::cin >> reads and converts in one step
Reading a number is so common that there is a shorter way. >> takes the next thing the user typed from std::cin and stores it in the variable on its right, converting it to that variable's type.
#include <iostream>
int main() {
int age = 0;
std::cout << "How old are you? ";
std::cin >> age;
std::cout << "Next year you will be " << age + 1 << ".\n";
}With 36 typed, the session is:
How old are you? 36
Next year you will be 37.Compare the arrows with output. In std::cout << age the value travels to the screen. In std::cin >> age it travels from the keyboard into the variable.
Use >> for numbers. It first skips any spaces and line breaks, then reads characters for as long as they fit the variable's type. With a std::string on the right, >> reads only up to the next space, so it would turn the name Ada Lovelace into Ada. Use std::getline to read text.
The shape of an interactive program
Most small programs follow the same four steps: prompt, read, compute, print.
Here is the whole shape in one program. It asks for the sides of a rectangle and prints its area.
#include <iostream>
int main() {
double width = 0;
double height = 0;
std::cout << "Width in metres: ";
std::cin >> width;
std::cout << "Height in metres: ";
std::cin >> height;
double area = width * height;
std::cout << "Area: " << area << " square metres\n";
}With 2.5 and 4 typed as the two answers, it prints Area: 10 square metres. Try it in the playground with two lines of standard input.
One trap: a line of text after a number
>> stops reading at the end of the number. The Enter that the user pressed after it is still waiting to be read. If the next read is std::getline, it sees that leftover end of line at once and stores an empty line, without waiting for the user.
#include <iostream>
#include <string>
int main() {
int age = 0;
std::string name;
std::cout << "How old are you? ";
std::cin >> age;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "! You are " << age << ".\n";
}The user types 36 and never gets the chance to type a name:
How old are you? 36
What is your name? Hello, ! You are 36.The fix is to skip the leftover before reading the line. std::cin >> std::ws; reads and throws away spaces and line breaks ("ws" is short for "white space") and stops in front of the next visible character:
std::cout << "What is your name? ";
std::cin >> std::ws;
std::getline(std::cin, name);You need this only when std::getline comes after >>. A program that reads its lines of text first, or reads only numbers, never meets the problem.
Three errors you will meet
Forgetting std:: in front of string. This is the first long error message of the course. The compiler prints about thirty lines for it; here are its beginning and its end.
#include <iostream>
int main() {
string name;
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}main.cpp: In function 'int main()':
main.cpp:4:5: error: 'string' was not declared in this scope
4 | string name;
| ^~~~~~
...
main.cpp:5:28: error: 'name' was not declared in this scope; did you mean 'tzname'?
5 | std::getline(std::cin, name);
| ^~~~
| tznameDo not try to read all of a long message. Find the first line that contains error: line 4, 'string' was not declared in this scope. The compiler does not know a type called string; its full name is std::string. The lines left out here are notes listing names the compiler thinks you might have meant, and std::string is among them.
The second error, about name, is only a consequence of the first: line 4 failed, so the variable was never created. Fix the first error, compile again, and both disappear.
Text that is not a number. There is no error message for this one. If the user answers ten to std::cin >> age;, the characters do not fit an int. The read fails, age is set to 0, and the program carries on with the wrong value. std::stoi("ten") is stricter. It stops the program with:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoiThis message appears while the program is running, not while it is being compiled, because only then is the text known. invalid_argument says a function was given a value it cannot use, and the last line names the function: stoi. For now, assume the user types sensible numbers; later courses show how to check and ask again.
Reading more than was typed. On this site the input is the lines you provided in advance. If your program reads when none are left, the read fails quietly and the variable keeps the value it already had. In the graded exercises the tests tell you directly: "the program tried to read more input than the user typed". Check that your program reads exactly as many times as it should.
What you can do now
You can prompt the user, read a line of text or a number, convert text to a number and print a result that depends on what was typed. In the exercises you will predict what conversions produce, then write a program that holds a short conversation.
Next: make decisions, so that a program can respond differently to different answers.