ifstream from stdin

P

Paulo da Silva

How can I use a ifstream object to input from stdin?

Ex.
ifstream inf;
if (fn=="-")
{ what here to use inf as cin?
}
else
{ inf.open(fn.c_str,ios::in);
}
inf >> ...

Thanks.
 
P

Paulo da Silva

Robert Bauck Hamar escreveu:
istream *inf;


inf = &cin;


inf = new ifstream(fn.c_str());


*inf >> ...

...

if (inf == &cin) !=
delete inf;

Thank you. This works ...
 
J

James Kanze

On some systems, opening "/dev/stdin" might work, but the general solution
is to use a pointer:

Or a reference.
istream *inf;
inf = &cin;
inf = new ifstream(fn.c_str());
*inf >> ...

if (inf == &cin)
delete inf;

More frequent, I think, is something along the lines of:

if ( argc == 1 ) {
process( std::cin ) ;
} else {
for ( int i = 1 ; i < argc ; ++ i ) {
std::ifstream in( argv[ i ] ) ;
if ( ! in ) {
std::cerr << "Could not open: " << argv[ i ] <<
std::endl ;
} else {
process( in ) ;
}
}
}

All the work is then done in "process( std::istream& )".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,137
Latest member
IndiraMcCo

Latest Threads

Top