Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is cin a proper file object?

Tags:

c++

file

stdin

As in, can I pass cin to any function that accepts an ifstream object?

like image 503
Jeffrey Aylesworth Avatar asked Mar 13 '10 03:03

Jeffrey Aylesworth


People also ask

What is CIN in C language?

The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source.

What does Cin return in C++?

cin >> num1 returns a reference to cin . If cin >> num1 is able to read an int , cin continues to be in a good state; if the attempt at input fails, cin is set to a state that is not good. In if (cin) , the condition is true if cin is in a good state.

How does cin and cout work?

cin is an object of the input stream and is used to take input from input streams like files, console, etc. cout is an object of the output stream that is used to show output. Basically, cin is an input statement while cout is an output statement. They also use different operators.

Which is the correct code to create a file stream object which opens a file for output?

Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects. void open(const char *filename, ios::openmode mode);


2 Answers

std::cin is not a file stream, but an input stream, or istream. You can pass it to any function that accepts an istream.

like image 57
Nate W. Avatar answered Oct 05 '22 12:10

Nate W.


std::cin is a std::istream.

There is little difference between class istream and its derivative ifstream. ifstream allows you to open and close files, providing open(), close(), and is_open(), and a constructor which calls open() — and that's it!

If your function doesn't use those methods, it should take an istream& instead of an ifstream&.

like image 35
Potatoswatter Avatar answered Oct 05 '22 11:10

Potatoswatter