Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Chaucer

using "cin" for input from file?

This topic is 5714 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can the "cin" command from iostream be used to get input from a file? If so, how can it be used in such a way?

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
Why would you want to? Why not use fstream?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
cin isn''t a function anyway. Its a static instance of a istream(I think its istream...Correct me if I am wrong).

Share this post


Link to post
Share on other sites
cin is NOT a function. It is a global variable.

If you want to redirect it, you need to use the rdbuf member function :


    
#include <fstream> // NEVER <iostream.h> !!!!


#include <iostream> // NEVER <iostream.h> !!!!


#include <streambuf>

using namespace std;

int main()
{
ifstream ifs( "input.txt" );

// You MUST save the stdin buffer

// and restore it at the end of the program.

streambuf* cin_buffer = cin.rdbuf();

// Assign ifs's ifstreambuf to cin

// You could have used any other istreambuf,

// user-defined or whatever.

cin.rdbuf( ifs.rdbuf() );

// Now cin points to "input.txt"


int read_from_file;
cin >> read_from_file;

// Must restore, otherwise cin won't have

// a valid stream to close after ifs is

// destroyed.

cin.rdbuf( cin_buffer );
}


Watch out what you're doing though.

Note that this wont't work with the old iostream (.h) library.

edit: was writing to an istream ... how embarassing.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]


[edited by - Fruny on October 2, 2002 11:09:51 AM]

Share this post


Link to post
Share on other sites
Sorry, I didn''t mean to call cin a function.

Lets just say someone else wrote a bunch of code using cin and I''d like to be able to change the usage of cin to read from a file instead of changing all of the code.

Share this post


Link to post
Share on other sites
or!

do something like this (from the command prompt):

>type filename | program_that_uses_cin


on *nix it would be:

>cat filename | program_that_uses_cin


type/cat outputs the contents of the file to stdout. What the | thingie does is pipe the left programs stdout (cout) to the right programs stdin (cin)

Share this post


Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!