Adam
Adam

Reputation: 335

declaring input stream

I have a C++ code with

ifstream myfile;
myfile.open("input");

and then has commands like:

myfile.getline(inp,256);

Question: How can I modify myfile.open("input") so that myfile is associated with cin instead of "input"?

I don't want to change all myfile.getline commands to cin.getline.

Declaring myfile=cin does not compile.

Upvotes: 0

Views: 1301

Answers (4)

Dietmar Kühl
Dietmar Kühl

Reputation: 154005

If you insist in using an std::ifstream you can replace the std::streambuf of the base std::istream (std::ifstream overloads rdbuf() so you can't use it directly):

std::ifstream file;
if (use_cin) {
    file.std::istream::rdbuf(std::cin.rdbuf());
}

Upvotes: 0

Seg Fault
Seg Fault

Reputation: 1351

You can put your code into a function that takes a reference to a std::istream, e.g.

void process_data( std::istream & istr )
{ ... }

Then you can call this function both with any std::ifstream and with std::cin:

std::ifstream myfile;
...
process_data( myfile );
process_data( std::cin );

Upvotes: 1

Puppy
Puppy

Reputation: 146998

Separate it out into a function and take the std::istream& as an argument. Then you can execute on both std::cin and myfile as you wish.

Upvotes: 2

hmjd
hmjd

Reputation: 122001

Use an istream& reference instead:

std::istream& myfile(std::cin);

Upvotes: 3

Related Questions