#ifndef INPUT_WRAPPER_H #define INPUT_WRAPPER_H #include #include #include #include class InputWrapper { private: std::streambuf *inbuf; std::ifstream fin; public: InputWrapper(int argc, const char* argv[]) : inbuf(NULL) { if (argc>1) { fin.open(argv[1]); if (fin.is_open()) { inbuf = std::cin.rdbuf(fin.rdbuf()); } else { std::cout << "Input file '" << argv[1] << "' not found.\n"; std::cout << "Defaulting to keyboard input.\n\n"; } } } ~InputWrapper() { if (inbuf) std::cin.rdbuf(inbuf); // restore cin } // raises runtime_error on end of input std::string generalQuestion(const std::string& prompt="") { std::cout << prompt; bool done(false); std::string response; while (!done) { if (getline(std::cin, response)) { if (inbuf) std::cout << response << std::endl; // echo input from file if (response.length() > 0) done = true; } else { if (inbuf) { // switch back to keyboard input std::cin.clear(); std::cin.rdbuf(inbuf); inbuf = NULL; } else { throw std::runtime_error("unexpected end of input reached."); } } } return response; } }; #endif