Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.

Similar presentations


Presentation on theme: "1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives."— Presentation transcript:

1 1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives (reads) or transmits (writes) a sequence of bytes. The reading and writing functions handle the streaming of bytes between the devices and memory.

2 2 cin cin is an object of type istream (input stream), associated with the standard input device (the keyboard). Use the stream extraction operator (>>) to extract bytes from the input stream and into a variable int value; cin >> value; int amount; double tax; cin >> amount >> tax;

3 3 cout cout is an object of type ostream (output stream), associated with the standard output device (the monitor). Use the stream insertion operator << to insert bytes from the variable to the output stream. int value = 5; cout << value; int amount = 40; double tax = 8.2; cout << amount << tax;

4 4 type-safe I/O > are overloaded to accept data of different types If unexpected data is processed, an error bit is set. You can check the values of the error bits to see if I/O was successful int value = 5; char *str = "Hello"; char c = ' ' cout << value << c << str;

5 5 error bits eofbit An input operation reached the end of the input sequence This bit is set when an attempt is made to read past the end of file. failbit An input or output operation failed to read/write the expected item. For example, cin expected to read a double but found a char instead. badbit An error occurred that resulted in loss of data. A possible cause for this might be memory shortage. goodbit Everything is fine. This bit is 1 as long as all of the above are 0.

6 6 error bits There are several member functions that allow you to check the error state: bool eof() True if the eofbit is set, false otherwise bool fail() True if the failbit or badbit is set, false otherwise bool bad() True if the badbit is set, false otherwise bool good() True if no error bit is set, false otherwise

7 7 error bits iostate rdstate() This function returns the current status of the error flags. Example: void clear() This function restores a stream's state to good. if (cin.rdstate() == ios::goodbit) cout << "Everything is fine" << endl; if (cin.rdstate() == ios::eofbit) cout << "End of file" << endl;


Download ppt "1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives."

Similar presentations


Ads by Google