C++ Stream Input/Output: C++ Stream Input/Output Outline
1 Introduction
2 Streams
2.1 Classic Streams vs. Standard Streams
2.2 iostream Library Header Files
2.3 Stream Input/Output Classes and Objects
3 Stream Output
3.1 Output of char * Variables
3.2 Character Output using Member Function put
4 Stream Input
4.1 get and getline Member Functions
4.2 istream Member Functions peek, putback and ignore
4.3 Type-Safe I/O
5 Unformatted I/O using read, write and gcount
C++ Stream Input/Output: C++ Stream Input/Output Outline
6 Introduction to Stream Manipulators
6.1 Integral Stream Base: dec, oct, hex and setbase
6.2 Floating-Point Precision (precision, setprecision)
6.3 Field Width (width, setw)
6.4 Programmer-Defined Manipulators
7 Stream Format States and Stream Manipulators
7.1 Trailing Zeros and Decimal Points (showpoint)
7.2 Justification (left, right and internal)
7.3 Padding (fill, setfill)
7.4 Integral Stream Base (dec, oct, hex, showbase)
7.5 Floating-Point Numbers; Scientific and Fixed Notation (scientific, fixed)
7.6 Uppercase/Lowercase Control (uppercase)
7.7 Specifying Boolean Format (boolalpha)
8 Setting and Resetting the Format State via Member-Function flags
9 Stream Error States
10 Tying an Output Stream to an Input Stream
iostream Library Header Files: iostream Library Header Files iostream library
Has header files with hundreds of I/O capabilities
Standard input (cin)
Standard output (cout)
Unbuffered error (cerr)
Buffered error (clog)
Formatted I/O with parameterized stream manipulators
File processing operations
Stream Input/Output Classes and Objects: Stream Input/Output Classes and Objects >
Stream insertion and extraction operators
cin
istream object
Connected to standard input (usually keyboard)
cin >> grade;
Compiler determines data type of grade
Calls proper overloaded operator
No extra type information needed
Stream Input/Output Classes and Objects: Stream Input/Output Classes and Objects cout
ostream object
Standard output (usually display screen)
cin << grade;
As with cin, no type information needed
cerr, clog
ostream objects
Connected to standard error device
cerr outputs immediately
clog buffers output
Outputs when buffer full or flushed
Performance advantage (discussed in OS classes)
Stream Output: Stream Output Output
Use ostream
Formatted and unformatted
Standard data types (<<)
Characters (put function)
Integers (decimal, octal, hexadecimal)
Floating point numbers
Various precision, forced decimal points, scientific notation
Justified, padded data
Uppercase/lowercase control
Output of char * Variables: Output of char * Variables C++ determines data type automatically
Generally an improvement (over C)
Try to print value of a char *
Memory address of first character
Problem
<< overloaded to print null-terminated string
Solution: cast to void *
Use whenever printing value of a pointer
Prints as a hex (base 16) number
Slide8: 1 // Fig. 12.3: fig12_03.cpp
2 // Printing the address stored in a char * variable.
3 #include
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 char *word = "test";
11
12 // display value of char *, then display value of char *
13 // static_cast to void *
14 cout ( word ) is: "
16 ( word ) ( word ) is: 0046C070
Character Output using Member Function put: Character Output using Member Function put put function
Outputs characters
cout.put( 'A' );
May be cascaded
cout.put( 'A' ).put( '\n' );
Dot operator (.) evaluates left-to-right
Can use numerical (ASCII) value
cout.put(Â 65Â );
Prints 'A'
Stream Input: Stream Input Formatted and unformatted input
istream
>> operator
Normally skips whitespace (blanks, tabs, newlines)
Can change this
Returns 0 when EOF encountered
Otherwise, returns reference to object
cin >> grade
State bits set if errors occur
Discussed in 12.7 and 12.8
get and getline Member Functions: get and getline Member Functions get function
cin.get()
Returns one character from stream (even whitespace)
Returns EOF if end-of-file encountered
End-of-file
Indicates end of input
ctrl-z on IBM-PCs
ctrl-d on UNIX and Macs
cin.eof()
Returns 1 (true) if EOF has occurred
Slide12: 1 // Fig. 12.4: fig12_04.cpp
2 // Using member functions get, put and eof.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 int character; // use int, because char cannot represent EOF
12
13 // prompt user to enter line of text
14 cout << "Before input, cin.eof() is " << cin.eof() << endl
15 << "Enter a sentence followed by end-of-file:" << endl;
16
17 // use get to read each character; use put to display it
18 while ( ( character = cin.get() ) != EOF )
19 cout.put( character );
20
21 // display end-of-file character
22 cout << "\nEOF in this system is: " << character << endl;
23 cout << "After input, cin.eof() is " << cin.eof() << endl;
24
return 0;
26
27 } // end main
Slide13: Before input, cin.eof() is 0
Enter a sentence followed by end-of-file:
Testing the get and put member functions
Testing the get and put member functions
^Z
Â
EOF in this system is: -1
After input cin.eof() is 1
get and getline Member Functions: get and getline Member Functions get(charRef)
With character reference argument
Gets one character, stores in charRef
Returns reference to istream
If EOF, returns -1
get(charArray, size, delimiter)
Reads until size-1 characters read, or delimiter encountered
Default delimiter '\n'
Delimiter stays in input stream
Can remove with cin.get() or cin.ignore()
Makes array null-terminated
Slide15: 1 // Fig. 12.5: fig12_05.cpp
2 // Contrasting input of a string via cin and cin.get.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 // create two char arrays, each with 80 elements
12 const int SIZE = 80;
13 char buffer1[ SIZE ];
14 char buffer2[ SIZE ];
15
16 // use cin to input characters into buffer1
17 cout > buffer1;
19
20 // display buffer1 contents
21 cout << "\nThe string read with cin was:" << endl
22 << buffer1 << endl << endl;
23
24 // use cin.get to input characters into buffer2
25 cin.get( buffer2, SIZE );
Slide16: 26
27 // display buffer2 contents
28 cout << "The string read with cin.get was:" << endl
29 << buffer2 << endl;
30
31 return 0;
32
33 } // end main
Enter a sentence:
Contrasting string input with cin and cin.get
The string read with cin was:
Contrasting
The string read with cin.get was:
string input with cin and cin.get
get and getline Member Functions: get and getline Member Functions getline(array, size, delimiter)
Like last version of get
Reads size-1 characters, or until delimiter found
Default \n
Removes delimiter from input stream
Puts null character at end of array
Slide18: 1 // Fig. 12.6: fig12_06.cpp
2 // Inputting characters using cin member function getline.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 const int SIZE = 80;
12 char buffer[ SIZE ]; // create array of 80 characters
13
14 // input characters in buffer via cin function getline
15 cout << "Enter a sentence:" << endl;
16 cin.getline( buffer, SIZE );
17
18 // display buffer contents
19 cout << "\nThe sentence entered is:" << endl << buffer << endl;
20
21 return 0;
22
23 } // end main
Slide19: Enter a sentence:
Using the getline member function
Â
The sentence entered is:
Using the getline member function
istream Member Functions peek, putback and ignore: istream Member Functions peek, putback and ignore ignore()
Discards characters from stream (default 1)
Stops discarding once delimiter found
Default delimiter EOF
putback()
Puts character obtained by get() back on stream
peek()
Returns next character in stream, but does not remove
Type-Safe I/O: Type-Safe I/O >
Overloaded to accept data of specific types
If unexpected data processed
Error bits set
User can test bits to see if I/O failed
More in section 12.8
Unformatted I/O using read, write and gcount: Unformatted I/O using read, write and gcount Unformatted I/O
read (member of istream)
Input raw bytes into character array
If not enough characters read, failbit set
gcount() returns number of characters read by last operation
write (ostream)
Output bytes from character array
Stops when null character found
char buffer[] = "HAPPY BIRTHDAY";
cout.write( buffer, 10 );
Outputs first 10 characters
Slide23: 1 // Fig. 12.7: fig12_07.cpp
2 // Unformatted I/O using read, gcount and write.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 const int SIZE = 80;
12 char buffer[ SIZE ]; // create array of 80 characters
13
14 // use function read to input characters into buffer
15 cout << "Enter a sentence:" << endl;
16 cin.read( buffer, 20 );
17
18 // use functions write and gcount to display buffer characters
19 cout << endl << "The sentence entered was:" << endl;
20 cout.write( buffer, cin.gcount() );
21 cout << endl;
22
23 return 0;
24
25 } // end main
Slide24: Enter a sentence:
Using the read, write, and gcount member functions
The sentence entered was:
Using the read, writ
Introduction to Stream Manipulators: Introduction to Stream Manipulators Stream manipulators perform formatting tasks
Field widths
Precisions
Format flags
Fill character in fields
Flushing streams
Inserting newline in output stream
Skipping whitespace in input stream
Floating-Point Precision (precision, setprecision): Floating-Point Precision (precision, setprecision) Set precision of floating point numbers
Number of digits to right of decimal
setprecision stream manipulator
Pass number of decimal points
cout << setprecision(5)
precision member function
cout.precision(newPrecision)
With no arguments, returns current precision
Settings remain until changed explicitly
Slide27: 1 // Fig. 12.9: fig12_09.cpp
2 // Controlling precision of floating-point values.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::fixed;
9
10 #include
11
12 using std::setprecision;
13
14 #include // sqrt prototype
15
16 int main()
17 {
18 double root2 = sqrt( 2.0 ); // calculate square root of 2
19 int places;
20
21 cout << "Square root of 2 with precisions 0-9." << endl
22 << "Precision set by ios_base member-function "
23 << "precision:" << endl;
24
25 cout << fixed; // use fixed precision
Slide28: 26
27 // display square root using ios_base function precision
28 for ( places = 0; places <= 9; places++ ) {
29 cout.precision( places );
30 cout << root2 << endl;
31 }
32
33 cout << "\nPrecision set by stream-manipulator "
34 << "setprecision:" << endl;
35
36 // set precision for each digit, then display square root
37 for ( places = 0; places <= 9; places++ )
38 cout << setprecision( places ) << root2 << endl;
39
40 return 0;
41
42 } // end main
Slide29: Square root of 2 with precisions 0-9.
Precision set by ios_base member-function precision:
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
Â
Precision set by stream-manipulator setprecision:
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
Field Width (width, setw): Field Width (width, setw) width member function (base class ios_base)
cin.width(5)
Sets field width
Number of character positions for output
Maximum number of characters that should be input
Returns previous width
Fill characters/Padding
Used when output too small for width
Large outputs are printed (not truncated)
Can also use setw stream manipulator
When reading to char arrays
Reads 1 less character (leave room for null)
Slide31: 1 // Fig. 12.10: fig12_10.cpp
2 // Demonstrating member function width.
3 #include
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 int widthValue = 4;
12 char sentence[ 10 ];
13
14 cout > sentence ) {
19 cout.width( widthValue++ );
20 cout << sentence << endl;
21 cin.width( 5 ); // input 5 more characters from sentence
22 } // end while
23
24 return 0;
Slide32: 25
26 } // end main
Enter a sentence:
This is a test of the width member function
This
is
a
test
of
the
widt
h
memb
er
func
tion
Programmer-Defined Manipulators: Programmer-Defined Manipulators User-defined stream manipulators
Nonparameterized
Example
ostream& bell( ostream& output )
{
return output << '\a'; // issue system beep
}
\a - bell
\r - carriage return
\t - tab
Slide34: 1 // Fig. 12.11: fig12_11.cpp
2 // Creating and testing programmer-defined, nonparameterized
3 // stream manipulators.
4 #include
5
6 using std::ostream;
7 using std::cout;
8 using std::flush;
9
10 // bell manipulator (using escape sequence \a)
11 ostream& bell( ostream& output )
12 {
13 return output << '\a'; // issue system beep
14 }
15
16 // carriageReturn manipulator (using escape sequence \r)
17 ostream& carriageReturn( ostream& output )
18 {
19 return output << '\r'; // issue carriage return
20 }
21
Slide35: 22 // tab manipulator (using escape sequence \t)
23 ostream& tab( ostream& output )
24 {
25 return output << '\t'; // issue tab
26 }
27
28 // endLine manipulator (using escape sequence \n and member
29 // function flush)
30 ostream& endLine( ostream& output )
31 {
32 return output << '\n' << flush; // issue end of line
33 }
34
35 int main()
36 {
37 // use tab and endLine manipulators
38 cout << "Testing the tab manipulator:" << endLine
39 << 'a' << tab << 'b' << tab << 'c' << endLine;
40
41 cout << "Testing the carriageReturn and bell manipulators:"
42 << endLine << "..........";
43
44 cout << bell; // use bell manipulator
45
Slide36: 46 // use carriageReturn and endLine manipulators
47 cout << carriageReturn << "-----" << endLine;
48
49 return 0;
50
51 } // end main
Testing the tab manipulator:
a b c
Testing the carriageReturn and bell manipulators:
-----.....
Trailing Zeros and Decimal Points (showpoint): Trailing Zeros and Decimal Points (showpoint) showpoint
Forces decimal number to print with trailing zeros
For decimal number 79.0
79 without showpoint
79.000000 with showpoint (up to level of precision)
Reset with noshowpoint
Slide38: 1 // Fig. 12.13: fig12_13.cpp
2 // Using showpoint to control the printing of
3 // trailing zeros and decimal points for doubles.
4 #include
5
6 using std::cout;
7 using std::endl;
8 using std::showpoint;
9
10 int main()
11 {
12 // display double values with default stream format
13 cout << "Before using showpoint" << endl
14 << "9.9900 prints as: " << 9.9900 << endl
15 << "9.9000 prints as: " << 9.9000 << endl
16 << "9.0000 prints as: " << 9.0000 << endl << endl;
17
18 // display double value after showpoint
19 cout << showpoint
20 << "After using showpoint" << endl
21 << "9.9900 prints as: " << 9.9900 << endl
22 << "9.9000 prints as: " << 9.9000 << endl
23 << "9.0000 prints as: " << 9.0000 << endl;
24
return 0;
26
27 } // end main
Slide39: Before using showpoint
9.9900 prints as: 9.99
9.9000 prints as: 9.9
9.0000 prints as: 9
Â
After using showpoint
9.9900 prints as: 9.99000
9.9000 prints as: 9.90000
9.0000 prints as: 9.00000
Justification (left, right and internal): Justification (left, right and internal) left stream manipulator
Left-justified, padding to right
Right stream manipulator
Right-justified, padding to left
Can set padding/fill character
Next section
internal
Number's sign left-justified
Number's value right-justified
+ 123
showpos forces sign to print
Remove with noshowpos
Slide41: 1 // Fig. 12.14: fig12_14.cpp
2 // Demonstrating left justification and right justification.
3 #include
4
5 using std::cout;
6 using std::endl;
7 using std::left;
8 using std::right;
9
10 #include
11
12 using std::setw;
13
14 int main()
15 {
16 int x = 12345;
17
18 // display x right justified (default)
19 cout << "Default is right justified:" << endl
20 << setw( 10 ) << x;
21
22 // use left manipulator to display x left justified
23 cout << "\n\nUse std::left to left justify x:\n"
24 << left << setw( 10 ) << x;
25
Slide42: 26 // use right manipulator to display x right justified
27 cout << "\n\nUse std::right to right justify x:\n"
28 << right << setw( 10 ) << x << endl;
29
30 return 0;
31
32 } // end main
Default is right justified:
12345
Â
Use std::left to left justify x:
12345
Â
Use std::right to right justify x:
12345
Slide43: 1 // Fig. 12.15: fig12_15.cpp
2 // Printing an integer with internal spacing and plus sign.
3 #include
4
5 using std::cout;
6 using std::endl;
7 using std::internal;
8 using std::showpos;
9
10 #include
11
12 using std::setw;
13
14 int main()
15 {
16 // display value with internal spacing and plus sign
17 cout << internal << showpos << setw( 10 ) << 123 << endl;
18
19 return 0;
20
21 } // end main
+ 123
Padding (fill, setfill): Padding (fill, setfill) Set fill character used in padding
fill member function
cout.fill('*')
setfill stream manipulator
setfill( '^' )
Slide45: 1 // Fig. 12.16: fig12_16.cpp
2 // Using member-function fill and stream-manipulator setfill
3 // to change the padding character for fields larger the
4 // printed value.
5 #include
6
7 using std::cout;
8 using std::endl;
9 using std::showbase;
10 using std::left;
11 using std::right;
12 using std::internal;
13 using std::hex;
14 using std::dec;
15
16 #include
17
18 using std::setw;
19 using std::setfill;
20
Slide46: 21 int main()
22 {
23 int x = 10000;
24
25 // display x
26 cout << x << " printed as int right and left justified\n"
27 << "and as hex with internal justification.\n"
28 << "Using the default pad character (space):" << endl;
29
30 // display x with plus sign
31 cout << showbase << setw( 10 ) << x << endl;
32
33 // display x with left justification
34 cout << left << setw( 10 ) << x << endl;
35
36 // display x as hex with internal justification
37 cout << internal << setw( 10 ) << hex << x << endl << endl;
38
39 cout << "Using various padding characters:" << endl;
40
41 // display x using padded characters (right justification)
42 cout << right;
43 cout.fill( '*' );
44 cout << setw( 10 ) << dec << x << endl;
45
Slide47: 46 // display x using padded characters (left justification)
47 cout << left << setw( 10 ) << setfill( '%' ) << x << endl;
48
49 // display x using padded characters (internal justification)
50 cout << internal << setw( 10 ) << setfill( '^' ) << hex
51 << x << endl;
52
53 return 0;
54
55 } // end main
10000 printed as int right and left justified
and as hex with internal justification.
Using the default pad character (space):
10000
10000
0x 2710
Â
Using various padding characters:
*****10000
10000%%%%%
0x^^^^2710
Floating-Point Numbers; Scientific and Fixed Notation (scientific, fixed): Floating-Point Numbers; Scientific and Fixed Notation (scientific, fixed) Stream manipulator scientific
Forces scientific notation
1.946000e+009
Stream manipulator fixed
Forces fixed point format
Prints number of decimals specified by precision
1946000000.000000
If no manipulator specified
Format of number determines how it appears
Slide49: 1 // Fig. 12.18: fig12_18.cpp
2 // Displaying floating-point values in system default,
3 // scientific and fixed formats.
4 #include
5
6 using std::cout;
7 using std::endl;
8 using std::scientific;
9 using std::fixed;
10
11 int main()
12 {
13 double x = 0.001234567;
14 double y = 1.946e9;
15
16 // display x and y in default format
17 cout << "Displayed in default format:" << endl
18 << x << '\t' << y << endl;
19
20 // display x and y in scientific format
21 cout << "\nDisplayed in scientific format:" << endl
22 << scientific << x << '\t' << y << endl;
23
Slide50: 24 // display x and y in fixed format
25 cout << "\nDisplayed in fixed format:" << endl
26 << fixed << x << '\t' << y << endl;
27
28 return 0;
29
30 } // end main
Displayed in default format:
0.00123457 1.946e+009
Â
Displayed in scientific format:
1.234567e-003 1.946000e+009
Â
Displayed in fixed format:
0.001235 1946000000.000000
Uppercase/Lowercase Control (uppercase): Uppercase/Lowercase Control (uppercase) Stream manipulator uppercase
Uppercase E in scientific notation
1E10
Uppercase X in hex notation and uppercase hex letters
0XABCD
By default, lowercase
Reset with nouppercase
Slide52: 1 // Fig. 12.19: fig12_19.cpp
2 // Stream-manipulator uppercase.
3 #include
4
5 using std::cout;
6 using std::endl;
7 using std::uppercase;
8 using std::hex;
9
10 int main()
11 {
12 cout << "Printing uppercase letters in scientific" << endl
13 << "notation exponents and hexadecimal values:" << endl;
14
15 // use std:uppercase to display uppercase letters;
16 // use std::hex to display hexadecimal values
17 cout << uppercase << 4.345e10 << endl << hex << 123456789
18 << endl;
19
20 return 0;
21
22 } // end main
Slide53: Printing uppercase letters in scientific
notation exponents and hexadecimal values:
4.345E+010
75BCD15
Specifying Boolean Format (boolalpha): Specifying Boolean Format (boolalpha) Data type bool
Values true or false
Outputs 0 (false) or 1 (true) when used with <<
Displayed as integers
Stream manipulator boolalpha
Display strings "true" and "false"
Reset with noboolalpha
Slide55: 1 // Fig. 12.20: fig12_20.cpp
2 // Demonstrating stream-manipulators boolalpha and noboolalpha.
3 #include
4
5 using std::cout;
6 using std::endl;
7 using std::cin;
8 using std::boolalpha;
9 using std::noboolalpha;
10
11 int main()
12 {
13 bool booleanValue = true;
14
15 // display default true booleanValue
16 cout << "booleanValue is " << booleanValue << endl;
17
18 // display booleanValue after using boolalpha
19 cout << "booleanValue (after using boolalpha) is "
20 << boolalpha << booleanValue << endl << endl;
21
22 cout << "switch booleanValue and use noboolalpha" << endl;
23 booleanValue = false; // change booleanValue
24 cout << noboolalpha << endl; // use noboolalpha
25
Slide56: 26 // display default false booleanValue after using noboolalpha
27 cout << "booleanValue is " << booleanValue << endl;
28
29 // display booleanValue after using boolalpha again
30 cout << "booleanValue (after using boolalpha) is "
31 << boolalpha << booleanValue << endl;
32
33 return 0;
34
35 } // end main
booleanValue is 1
booleanValue (after using boolalpha) is true
Â
switch booleanValue and use noboolalpha
Â
booleanValue is 0
booleanValue (after using boolalpha) is false