ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Reading from Stdin in C++

Reading from Stdin in C++

by Jeffrey P. Bigham

The following code reads each line from the standard input (stdin) and outputs it on standard out (stdout). By using strings as opposed to char* we don't have to worry about overflowing the input buffer and can handle long lines effortlessly.

The code:


///////////////////////
// stdin input example
// using cin.getline
///////////////////////

#include <iostream>

using namespace std;

int main() {
  while(cin) {
    getline(cin, input_line);
    cout << input_line << endl;
  };

  return 0;
}

Compile with:


% g++ -o stdin_test stdin_test.cpp

Run with:


./stdin_test

Related Articles

  • Making I/O streams efficient in C++
  • ManticMoo.COM -> Jeff's Articles -> Programming Articles -> Reading from Stdin in C++