Reputation: 335
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
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
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
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