1.3 Input and Output
Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
std::cout
std::cout displays text or variable values on the screen. The << operator sends values into the output stream.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash\': single quote\": double quote\n: newline\t: tab
std::cout << "\"Hello\nWorld\"" << std::endl;Output:
"Hello
World"Formatting output
C++ can print several values by chaining <<.
int length = 10;
int width = 5;
double area = length * width;
std::cout << "Area = " << length << " * " << width << " = " << area << std::endl;Output:
Area = 10 * 5 = 50To control decimal places, include <iomanip> and use std::fixed with std::setprecision.
#include <iomanip>
std::cout << std::fixed << std::setprecision(2);
std::cout << "Area = " << area << std::endl;Output:
Area = 50.00Controlling the line ending
std::cout does not add a newline automatically. You can use std::endl or print \n yourself.
int num1 = 1, num2 = 2, num3 = 4, num4 = 8;
std::cout << num1 << ", ";
std::cout << num2 << ", ";
std::cout << num3 << ", ";
std::cout << num4 << "..." << std::endl;Output:
1, 2, 4, 8...std::cin
std::cin reads text from the keyboard and stores it in variables. The >> operator extracts values from the input stream.
Important: the variable type decides how the input is parsed. If r is a double, then std::cin >> r; reads a floating-point value.
#include <iostream>
#include <iomanip>
int main() {
double r;
std::cout << "Radius: ";
std::cin >> r;
double area = 3.14159 * r * r;
std::cout << std::fixed << std::setprecision(2);
std::cout << "Area = " << area << std::endl;
return 0;
}One possible run:
Radius: 5
Area = 78.54Here, std::cin >> r; reads one value and stores it directly into r.