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.
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.
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.
4 Comments