streams questions..

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.

Any suggestions?

Thank you.
Wasn't it file > program on most shells?
I want to do it from the program itself.
You can also redirect stuff directly. Try this for some fun:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
using namespace 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;
  }

Hope this helps.
Thank you. This is exactly what I was looking for.
Topic archived. No new replies allowed.