How to Read from stdin in C++ Posted in Polyglotbits on 01 of Dec, 2015

Reading from stdin in C++ is surprisingly concise. Only 12 lines of code (including includes and empty lines).

#include <iostream>
#include <string>

int main(int argc, char** argv)
  std::string line;
  int counter = 0;
  while (std::getline(std::cin, line)) {
    std::cout << counter << ": " << line << "\n";

We need the iostream header for access to std::cin and std::cout and we need the string header for - strings.

std::getLine reads from the stream (in our case, with std::cin, the stdin input stream) on a line by line basis, and writes the result into the line string object. This objects content is then written to std::cout (the stdout output stream) prefixed by the current line number.