As in, can I pass cin
to any function that accepts an ifstream object?
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.
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.
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.
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);
std::cin
is not a file stream, but an input stream, or istream
. You can pass it to any function that accepts an istream.
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&
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With