i/o question

D

Doug Harvey

Hi there. Just trying to figure out how to do something in c++

In "C", I would typically do something like this

FILE *inp = stdin; /* default to stdin *

if (input_file
inp = fopen(input_file)

/* ... *

I tried doing something like this in C++, but couldn't get anything t
compile
ifstream inp = &cin

but no go

Any suggestions would be appreciated, in addition to comments abou
whether there is a more appropriate way to do this in c++
dou

--
 
D

David White

Doug said:
Hi there. Just trying to figure out how to do something in c++.

In "C", I would typically do something like this:

FILE *inp = stdin; /* default to stdin */

In C stdin is a FILE*.
if (input_file)
inp = fopen(input_file);

/* ... */

I tried doing something like this in C++, but couldn't get anything to
compile:
ifstream inp = &cin;

In C++ cin is an istream, but not an ifstream. Nor is it a pointer. Try
this:
std::istream &inp = std::cin;

This makes inp a reference to the istream object cin, so you can use inp as
though it is cin.

DW
 
H

hacker++

Doug said:
In C stdin is a FILE*.

Try this:

std::ifstream file;
if(input_file)
{
file.open(input_file);
}

std::istream& inp = file.is_open() ? file : std::cin;

int a,b;

inp >> a >> b;
 

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

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,277
Latest member
VytoKetoReview

Latest Threads

Top