I/O with cin & cout
C++ handles console input and output through streams — objects that represent a flow of data in or out of your program. The two you’ll use constantly are std::cout for output and std::cin for input, both declared in <iostream>.
Output with std::cout
std::cout sends data to standard output (normally your terminal). The << insertion operator feeds values into the stream, and can be chained to print several values in sequence.
#include <iostream>
int main() {
int age = 30;
std::cout << "You are " << age << " years old." << std::endl;
return 0;
}You are 30 years old.
Input with std::cin
std::cin reads data from standard input (normally the keyboard). The >> extraction operator pulls values out of the stream into variables, and it too can be chained.
#include <iostream>
int main() {
std::string name;
int age;
std::cout << "Enter your name and age: ";
std::cin >> name >> age;
std::cout << "Hello, " << name << "! You are " << age << "." << std::endl;
return 0;
}std::cin >> name >> age reads two whitespace-separated tokens in one line — the first into name, the second into age. This works well for single words and numbers, but it stops at the first whitespace character, which causes trouble when you need a full line of text.
Reading a full line with std::getline()
To read an entire line, including spaces, use std::getline() instead of std::cin >>.
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Enter your full name: ";
std::getline(std::cin, fullName);
std::cout << "Hello, " << fullName << "!" << std::endl;
return 0;
}Error output with std::cerr
std::cerr is a separate output stream intended for error messages. It behaves like std::cout but writes to standard error instead of standard output, which lets error messages be separated from normal program output — useful when redirecting output to a file.
#include <iostream>
int main() {
std::cerr << "Warning: config file not found, using defaults." << std::endl;
return 0;
}A note on buffering
Output written to
std::coutisn't necessarily sent to the terminal immediately — it's often held in a memory buffer and "flushed" (actually written out) later for efficiency.Buffers get flushed automatically when the program ends normally, when the buffer fills up, or when explicitly requested (e.g.
std::endl,std::flush).Buffering is one of the reasons
std::endland"\n"behave slightly differently — covered in the next chapter on stream manipulators.