Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from cin or a file

Tags:

c++

istream

When I try to compile the code

istream in;
if (argc==1)
        in=cin;
else
{
        ifstream ifn(argv[1]);
        in=ifn;
}

gcc fails, complaining that operator= is private. Is there any way to set an istream to different values based on a condition?

like image 567
m42a Avatar asked Mar 09 '10 06:03

m42a


People also ask

What is CIN read in C++?

The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs.

Where does Cin read from?

cin is a predefined variable that reads data from the keyboard with the extraction operator ( >> ).

Why you don't want to use cin to read a string?

This can be considered as inefficient method of reading user input, why? Because when we read the user input string using cin then only the first word of the string is stored in char array and rest get ignored. The cin function considers the space in the string as delimiter and ignore the part after it.

Why do we use cin?

The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file.


1 Answers

You could use a pointer for in, e.g.:

istream *in;
ifstream ifn;

if (argc==1) {
     in=&cin;
} else {
     ifn.open(argv[1]);
     in=&ifn;
}
like image 119
dmcer Avatar answered Nov 20 '22 07:11

dmcer