views:

55

answers:

3

i was told that to redirect from standard input to file i need to do the following:

static std::ifstream inF("inpur.txt");
std::cin.rdbuf(inF.rdbuf());

and every call to std::cin will be redirected to input.txt. but my question is: do i need to open inF? and if i do, where do i need to do this?

+4  A: 

You opened it by calling it with the string constructor.

DeadMG
then why the inF.is_open() returning false?
or.nomore
Post the actual code. And `inpur.txt` looks like a mis-spelling.
dirkgently
@or.nomore: That can mean two things: Either the file could not be opened (e.g. doesn't exist), or you ran into the static initialization order fiasco (see http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14)
Space_C0wb0y
oh.. sure! that the problem, i didn't create it yet.
or.nomore
@or.nomore: It always helps to ask the real question in the first go ...
dirkgently
+1  A: 

Your code as-is fine. Do make a backup though of the original cin.rdbuf -- you may need to reset it in case of an error.

dirkgently
+2  A: 

That's the beauty. You already did so while declaring the object and passing the string to the explicit constructor of ifstream.

The file is opened in TEXT mode.

Refer this

Chubsdad