Archive for July, 2011

Streams in C++

July 7, 2011

C++ Streams Library exports two stream objects – cin and cout.
<< is called the stream insertion operator. >> is the stream extraction operator.

C++ provides a <fstream> header, that exports the ifstream and ofstream types. Note: ifstream and ofstream are types, unlike cin and cout, which are objects.
To create an ifstream that reads from a file,
ifstream myStream (“myfile.txt”);
int myInteger;
myStream >> myInteger;
You can also open a file by using ifstream’s open function.
ifstream myStream;
myStream . open (“myfile.txt”);
After trying to open a file, you should check if the stream is valid –
ifstream myStream (“myfile.txt”);
if ( ! myStream . is_open())
cerr << “Couldn’t open file” << endl;