C++ Basics Tutorial - Lesson 10
Related Blog Items
- C++ Basics - Tutorial
- C++ Tutorial Part 2 - Advanced
- C++ Advanced Tutorial - Lesson 11
- C++ Advanced Tutorial - Lesson 8
- C++ Advanced Tutorial - Lesson 3
Please refer lesson 9..
10. Stream IO
10.1 Iostream Library Header Files
10.2 Stream IO Classes and Objects
10.3 Output the address of a pointer
10.4 Method put
10.5 Stream Input
10.6 Unformatted IO
10.7 Stream manipulators
10.8 Stream Error States
10. Stream IO
10.1 Iostream Library Header Files
iostream.h contains basic information required for all stream-IO operations.
iomanip.h contains information useful for performing formatted IO with parameterized stream manipulators.
fstream.h contains information for user-controlled file processing operations.
10.2 Stream IO Classes and Objects
“iostream.h” contains many classes for handling a wide variety of IO operations. The istream class and ostream class are both derived from ios class. The iostream class is derived through multiple inheritance from both istream and ostream class.
cin is an object of istream class and cout is an object of ostream class. They are tied to standard input and output device such as keyboard and screen. Left-shift operator << is overloaded in the class as a stream-insertion operator to perform stream output, and right-shift operator >> is overloaded as a stream-extraction operator to perform stream input. These overloaded operators made it possible to perform IO with simple statement like
cin >> a; cout << b;
cerr and clog are objects of the ostream class and tied to the standard error device. Outputs to cerr is not buffered and outputs to clog is buffered.
10.3 Output the address of a pointer
When we output a pointer of a type other than char, the address of the object to which the pointer is pointing to is output. However, if we output a char pointer, the string will be output. To output the address of the string, we have to cast the char * to void *:
int main(int argc, char* argv[]) { Derived * derivedPtr = new Derived(111, 222); cout << "derivedPtr = " << derivedPtr << endl; char * charPtr = "Frank Liu"; cout << "charPtr = " << charPtr << endl; cout << "(void *)charPtr = " << (void *)charPtr << "\n\n"; return 0; }
Output will be:
derivedPtr = 0×00301A60
charPtr = Frank Liu
(void *)charPtr = 0×004270E4
10.4 Method put
The put method outputs one character:
cout.put( A ); put can be cascaded as cout.put( A ).put( B );
10.5 Stream Input
=>Stream Extraction Operator
A stream extraction operator reads from the input stream until a whitespace character such as a blank, tab and newline is encountered. The operator returns a reference to the object through which it is invoked (e.g. cin). But if the EOF is encountered, it will return zero. Therefore you can use a “while” loop to input a series of values:
while(cin >> a) {...}
=>get( ) and getline( )
Method get with no arguments inputs one character from the designated stream (even if it is whitespace) and returns it. It returns EOF if EOF is encountered.
Method get with a character argument inputs one character from the input stream (even if it is whitespace) and assign it to the character argument. It returns a reference to the object through which it is invoked (e.g. cin), and returns 0 when EOF is encountered.
Therefore, you can use a while loop to input a series of characters:
while(c = cin.get() != EOF) {...} while(cin.get(c)) {...}
The above two formats do the same job.
The third version of method get takes three arguments: a character array, a size limit, and a delimiter with default value ‘\n’:
const int size = 35; char array[size]; cin.get(array, size) // use default value '\n' as delimiter cin.get(array, size, '%') // use '%' as delimiter
This version reads characters from the input stream and load them into the character array, until (size - 1) characters had been read, or before that the delimiter is encountered. Finally a NULL character is inserted to the end of the inputted character string in the array.
When the delimiter is encountered, the method does not load it into the character array, and it remains in the input stream. Therefore, the next input method will get this delimitor such as a new line.
The getline method is the same as the third version of get, except that it reads in the delimiter character from the input stream and discard it.
=>ignore( )
The ignore method reads in and discards a number of characters (default is one) from the input stream, or until encounters a designated delimiter (default is EOF, which causes skipping to the end of the whole file).
=>putback( )
The putback method places the last character obtained by get method back to the input stream. It is useful when you check characters one by one with get method looking for a field beginning with a specific character. When you find this character you put it back to the input stream, so that other input statements can input it correctly.
=>peek( )
It is the combinition of get and putback. It returns next character in the input stream, but doesn’t remove that character from the stream.
10.6 Unformatted IO
Unformatted IO inputs or outputs a certain number of bytes without any format.
=>write( )
It has two arguments: a character array and the number of bytes to be outputted:
char * array = "ABCDEFGHIJKLMN"; cout.write(array, 5); // "ABCDE" will be outputted.
=>read( )
Its arguments are the same as write. If not enough bytes are read, failbit will be set.
=>gcount( )
It returns the number of bytes read by last input operation.
const int size = 80; char buffer[size]; cin.read(buffer, 20); cout.write(buffer, cin.gcount());
10.7 Stream manipulators
When a stream manipulator is inserted, the format of the following output are all determined by it, until a different manipulator is inserted again.
=>Parameterized Stream Manipulator
Stream Manipulators which take arguments are called parameterized stream manipulators, such as setprecision, setbase, etc. Their header file is
=>Integral Stream Base
Integers are by default interpreted as decimal values. To change the base, insert the manipulator “hex” for hexadecimal, “oct” for octal, and “dec” to change back to decimal. Or you can use parameterized stream manipulator setbase, whose arguments may be 8, 10 or 16.
int a = 11; cout << a << endl // "11" will be outputted << oct << a << endl // "14" will be outputted << hex << a << endl; // "B" will be outputted
=>Floating-Point Output Precision
The precision method or setprecision parameterized stream manipulator control the number of digits to the right of the decimal point. The precision method with no arguments returns the current precision setting:
int a = 3.14159265; cout << setprecision(2) << a; // "3.14" will be outputted cout.precision(4); cout << a // "3.1416" will be outputted cout << precision() << endl; // "4" will be outputted
It will affect all the following IO operations until specified again.
=>Field Width
Method width and parameterized stream manipulator setw sets the IO field width. Method width returns the previous width. If the actual width is smaller than the set width, fill characters are inserted as padding. If it is wider then the set width, the full number will be printed. It only affect one succeeding data.
When inputting characters with the width is set to n, only n-1 characters will be inputted, and the last character will be set to NULL.
Example using width method:
int w = 2; char c[10]; cin.width(3); while(cin >> c) { cout.width(w++); cout << c << endl; cin.width(3); }
When you input abcdefghijklnmopqrstuvwxyz , the output will be
ab
cd
ef
gh
ij
kl
nm
op
qr
st
uv
wx
yz
Example using setw stream manipulator:
int w = 4; char c[10]; while(cin >> setw(5) >> c) cout << setw(w++) << c << endl;
=>Format State Flags
ios::skipws //Skip whitespace characters on an input stream ios::left //Left justify ios::right //Right justified ios::internal //Number s sign (+, -) left justified, magnitude right justified ios::dec //Integer treated as decimal ios::oct //Integer treated as octal ios::hex //Integer treated as hexadecimal ios::showbase //Put 0 in front of octal numbers, 0x or 0X before hexadecimal, to indicate the base ios::uppercase //Use 0X instead of 0x for hexadecimals, and E instead of e for scientific notion ios::showpoint //Float numbers should be outputted with a decimal point. Normally used with ios::fixed //to guarantee a certain number of digits to the right of //the decimal point. For floating-point-format output. ios::fixed //Float numbers should be outputted with a specific //number of digits to the right of the decimal point. //Specially for floating-point format. ios::showpos //the positive sign should be shown ios::scientific //Outputs a number in scientific notion
The static data member ios::adjustfield flag includes the bits left, right, and internal. The ios::basefield includes the oct, hex and dec bits. The ios::floatfield contains the flags scientific and fixed.
All of these format state flags are defined as enums in class ios. They represent different bits of one long format state number, which is the settings of the IO stream.
The flags, setf and unsetf methods and setiosflags and resetiosflags parameterized stream manipulators set and reset these flags.
The flags method sets a number of flags and returns the previous settings. In its parameter list, you can or different flags with | . Any flags not specified in the list is reset. The unsetf and the two manipulators works similarly.
The setf method sets one flag and the rest remains the same. When two flags separated with “,” are listed:
cout.setf( ios::left, ios::adjustfield );
the first is set, the second is reset.
All of this format state flags affect all the following IO operations until specified again.
float a = 7.6; float b = 333.14159; cout << setw(20) << setprecision(3) << setiosflags(ios::internal | ios::showpos | ios::scientific) << a << endl; cout << setw(20) << b << endl;
Output will be:
+ 7.600e+00
+ 3.331e+02
=>Padding (fill, setfill)
The fill method and setfill stream manipulator set the padding character. Default is space character.
float a = 3.3; cout << setw(8) << setfill( # ) << a;
will have an output
#####3.3
10.8 Stream Error States
The state of a stream may be tested through bits in ios class.
=>eofbit and eof( ) Method
The eofbit is automatically set for an input stream when EOF is encountered. When EOF is encountered on cin, the call cin.eof returns true. Here encounter means that there is no more bytes to read from the input stream. It does not mean that the reading method has already hitted the wall.
=>failbit and fail( ) Method
The failbit is set and fail method returns true when recoverable format error occurs on the IO stream. When EOF is encountered during input, failbit is set for cin.
=>badbit and bad( ) Method
The badbit is set and bad method returns true when irrecoverable lost-data error occurs on the IO stream.
=>goodbit and good( ) Method
The goodbit is set and good method returns true when neither of the above errors occurs.
=>clear( ) Method
The clear method is normally used to restore a stream’s state to good so that IO may proceed on that stream. Any error state bit listed above which becomes the argument is set. The default argument of clear method is ios::goodbit, so the statement cin.clear clears cin and sets goodbit for the statement, and cin.clear(ios::failbit) actually sets the failbit.
Popularity: 7%
You need to log on to convert this article into PDF
Related Blog Items - C++ Basics - Tutorial
- C++ Tutorial Part 2 - Advanced
- C++ Advanced Tutorial - Lesson 11
- C++ Advanced Tutorial - Lesson 8
- C++ Advanced Tutorial - Lesson 3
Related Blog Items
- C++ Basics - Tutorial
- C++ Tutorial Part 2 - Advanced
- C++ Advanced Tutorial - Lesson 11
- C++ Advanced Tutorial - Lesson 8
- C++ Advanced Tutorial - Lesson 3
No Comments
No comments yet.