Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
cout
cout displays text or values. Add << endl at the end of the output expression when a new line is needed.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash\': single quote\": double quote\n: newline\t: tab
cout << "\"Hello" << endl;
cout << "World\"" << endl;Output:
"Hello
World"KNOWLEDGE QUIZ
Formatted output
Use fixed together with setprecision() to control the number of decimal places, then chain text and values with <<.
fixed: use fixed-point notationsetprecision(2): keep two digits after the decimal point<<: send each following value to the output stream
cout << fixed << setprecision(2)
<< "Area = " << length << " * " << width << " = " << area << endl;Output:
Area = 10 * 5 = 50.00fixed << setprecision(2) selects fixed-point formatting with two decimal places.
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
int length = 10;
int width = 5;
double area = length * width;
cout << fixed << setprecision(2) << "Area = " << length << " * " << width << " = " << area << endl;
return 0;
}KNOWLEDGE QUIZ
Controlling the line ending
cout does not add a new line automatically, so outputs can be chained; add << endl when the current line should end.
int num1 = 1;
int num2 = 2;
int num3 = 4;
int num4 = 8;
cout << num1 << ", ";
cout << num2 << ", ";
cout << num3 << ", ";
cout << num4 << "..." << endl;Output:
1, 2, 4, 8...cin input
cin reads standard input with the extraction operator >>; the destination variable's type controls parsing.
cin >> word can store one token in a string, while int and double variables receive numeric input.
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
cout << "Radius: " << endl;
double r;
cin >> r;
double area = 3.141592653589793 * pow(r, 2);
cout << fixed << setprecision(2) << "Area = " << area << endl;
return 0;
}One possible run:
Radius: 5
Area = 78.54Here, cin reads a double directly, while 3.141592653589793 is the numeric value of pi used in this example.
KNOWLEDGE QUIZ
Output Lab Bench
Run the three code cards in order and watch how each statement changes the terminal.
Calculate the distance between two points
Read two coordinate points and print the planar distance.
- Read x1, y1, x2, and y2 as four floating-point numbers.
- Apply the distance formula to compute the result.
- Print the distance rounded to two decimal places.
Build a temperature record card
Read one Celsius value, store it in clearly named variables, convert it to Fahrenheit, and print a compact report.
- Read one Celsius value with cin.
- Store the Fahrenheit result in a variable named fahrenheit.
- Create a string variable named reportTitle and print it together with the converted value.