Copy stdin to stdout the C++ Way

March 25, 2014
Recently, there was a blog post I found through Hacker news where he talks about an interview question that many people fail to be able to answer using Java.
My current employer uses an online quiz to pre-screen applicants for open positions. The first question on the quiz is a triviality, just to let the candidate get familiar with the submission and testing system. The question is to write a program that copies standard input to standard output. Candidates are allowed to answer the questions using whatever language they prefer.

I found many of the potential answers, and subsequent rebuttals, in the Hacker News comments to be interesting. If I was going to answer the question using C++, I would answer with one of the following.

It doesn't get much simpler than this.

#include <iostream>
 
int main ()
{
    std::cout << std::cin.rdbuf();
    return 0;
}

For a more flexible approach that would lead into say, copying files, this would be a start.

#include <fstream>
 
int main ()
{
   std::ifstream in("/dev/stdin");
   std::ofstream out("/dev/stdout");
   out << in.rdbuf();
   return 0;
}

It's actually surprising how verbose and how many corner cases there are in Java to handle this with the same amount of flexibility, completeness, and speed.

Related Posts

4 Comments

Comment March 25, 2014 by Alessandro Stamatto
I didn't know about rdbuf() , neither what it's "<<" operator does. Now I know! Since I didn't know about it, I would try that for this question: char c; while (cin >> noskipws >> c) cout << c; Is it correct? I dunno!
Comment March 25, 2014 by Alessandro Stamatto
Damn, my comment was eaten! Rewriting it: I didn't know about rdbuf(), neither what it's output ('shift-left operator') did. I would've tried something like that on that question: https://gist.github.com/astamatto/f265729f3756c9006024
Comment March 25, 2014 by Mark Dominus
You may be interested to see the Haskell version: main = interact id Or the Perl version: print while <>; I suspect the Python version is similarly trivial, but I don't know it offhand.
Comment March 26, 2014 by puplan
Just a tad simpler: #include <iostream> void main () { std::cout << std::cin.rdbuf(); }