I want the cin stream in my program to take input from another stream (I want to preload it with a content of a file) rather than from the keyboard input. I know that what I want is not standard, but I am just curious if some kind of a hack is possible. I think it is not possible directly to do directly, but may be there is a buffer I can fill at the beginning of the program.
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
usingnamespace std;
int main( int argc, char** argv )
{
if (argc != 2)
{
cout << "usage:\n " << argv[ 0 ] << " FILENAME\n\n""Echoes the contents of FILENAME to the screen.\n";
return 0;
}
// save the current stdin streambuf
streambuf* cinsb = cin.rdbuf();
// redirect stdin to this file
ifstream f( argv[ 1 ] );
cin.rdbuf( f.rdbuf() );
// while the file (std input) is available, read and echo it
string s;
while (getline( cin, s ))
cout << s << endl;
// EOF (or other error): reset stdin to its original value
cin.clear();
cin.rdbuf( cinsb );
f.close();
// Now we use the original stdin to PAUSE
cout << "Press ENTER to continue..." << flush;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
return 0;
}