How to Read from stdin in C++
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)) {
counter++;
std::cout << counter << ": " << line << "\n";
}
}
We need the iostream header for access to stdcin and stdcout and we need the string header for - strings.
stdgetLine reads from the stream (in our case, with stdcin, 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.