Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redirect an ifstream to cin?

Tags:

c++

ifstream

I have a program that reads input from the terminal and the stream from cin is used in multiple classes for parsing at various levels.

Instead of using cin for getting the data from the terminal, I want to read in a file that has the information I need to parse, but I don't want to modify all my header and .cpp files to accept an ifstream& parameter.

To keep the existing code in place I'm trying to simply redirect the ifstream to cin, but don't know how.

So assume I have the following in main:

ifstream inFile("myfile.txt", ifstream::io);

string line;
while(getline(inFile, line)) 
{
  char firstChar;
  inFile >> firstChar;
  cout << firstChar;
  inFile.ios::rdbuf(cin.rdbuf());
  Continue myFile;
} 

In my continue.cpp I'm just doing:

Continue()
{
   string line;
   cin >> line;
   cout << "---remaining line: " << line << "\n";
}

However it's only printing the first char from main.

like image 695
hax0r_n_code Avatar asked Oct 26 '25 01:10

hax0r_n_code


2 Answers

Simply swap pointers to std::streambuf:

ifstream file("myfile.txt");
string line;
if (file.is_open()) {
    cin.rdbuf(file.rdbuf());  // swap
    cin >> line;
}
std::cout << line;
like image 118
Lukáš Bednařík Avatar answered Oct 27 '25 14:10

Lukáš Bednařík


istream objects read from a std::streambuf, and that can be swapped in an out. The relevant member function is .rdbuf

like image 44
MSalters Avatar answered Oct 27 '25 14:10

MSalters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!