C++ Standard Streams

For every program C++ provides the POSIX standard streams—standard input, standard output, and standard error—for input and output. These streams are automatically available without needing to open or close them.

Standard Output (std::cout)

std::cout (pronounced "see-out") is the standard output stream. It's used to display information to the console. You use the insertion operator (<<) to send data to std::cout.

#include <iostream>

int main() {
  std::cout << "Hello, world!" << std::endl; // Output to the console
  int age = 30;
  std::cout << "My age is " << age << ".\n";  // Chaining output
  return 0;
}

std::endl inserts a newline character and flushes the output buffer, ensuring the output is displayed immediately. \n inserts a newline, but does not flush.

Standard Input (std::cin)

std::cin (pronounced "see-in") is the standard input stream. It's used to receive input from the keyboard. You use the extraction operator (>>) to read data from std::cin.

#include <iostream>
#include <string>

int main() {
  std::string name;
  std::cout << "Enter your name: ";
  std::cin >> name; // Read a word

  int age;
  std::cout << "Enter your age: ";
  std::cin >> age; // Read an integer

  std::cout << "Hello, " << name << "! You are " << age << " years old.\n";

  std::string fullName;
  std::cout << "Enter your full name: ";
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Clear the buffer (important!)
  std::getline(std::cin, fullName); // Read a line, including spaces
  std::cout << "Your full name is: " << fullName << std::endl;

  return 0;
}

std::getline(std::cin, string_variable) is used to read an entire line of input, including spaces. It's often used after reading other input with >> to clear the input buffer.

Standard Error (std::cerr and std::clog)

std::cerr (pronounced "see-err") is the standard error stream. It's used to output error messages. It is typically unbuffered, so output appears immediately, even if other output is buffered. std::clog is also for error output but is buffered.

#include <iostream>

int main() {
  if (/* some error condition */) {
    std::cerr << "An error occurred!" << std::endl;
    return 1; // Indicate an error
  }
  return 0;
}

Using std::cerr for errors allows you to separate error messages from regular output, which is useful for debugging and logging.