Chapter 6 Objects and Classes - Sun Yat

Download Report

Transcript Chapter 6 Objects and Classes - Sun Yat

Chapter 10
Console I/O Operations
§10.1 C++ Stream & C++ Stream Classes
§10.2 Unformatted I/O Operations
§10.3 Formatted Console I/O Operations
§10.4 Managing Output with Manipulators
Input and Output?

How to provide the input data & present results?


cin >> and cout <<
How to control the format of input and output?

C++ supports a rich set of I/O functions and operations



C++ supports all of C’s rich set of I/O functions
These functions and operations use the advanced features of
C++: classes, inheritance, polymorphism
Using stream and stream classes to implement its I/O
operations


with the console (this chapter), and
with disk files(next chapter).
2
§10.1 C++ Stream

Stream: an interface to operate on different I/O systems




Display/terminals, hard disks, flash disks, etc…
Independent of the actual device
A stream is a sequence of bytes
A program extracts the bytes from an input stream and
inserts bytes into an output stream
Input stream
Extract
Program
Insert
Input
device
Output stream
Output
device
3
About C++ Stream

A C++ program handles data (input/output)
independent of the devices used.

The data in the input stream can come from the
keyboard or any other storage device.

The data in the output can go to the screen or
any other storage device :
4
The cin/cout stream

Pre-defined streams

Automatically opened when a program begins its
execution.

Standard input/output stream

Connected to the standard input/output devices

Usually the keyboard/screen.

Can redirect streams to other devices or files
freopen("test.txt", "r", stdin);
freopen("test.txt", "w", stdout);
cout<<“Test it.”<<endl;
C++ Stream Classes

Stream classes for console I/O operations:

These classes are declared in the header file iostream:


Eg: include <iostream>
ios is declared as the virtual base class
ios
istream
get(), read(), getline()
overloading <<
streambuf
ostream
put(), write()
overloading >>
iostream
istream_withassign
cin
iostream_withassign
ostream_withassign
cout
§10.2 Unformatted I/O Operations


Using cin/cout, an istream/ostream object
Operators >> and <<


Overloaded in istream/ostream to recognize all the
basic C++ types.
General format for cin and cout:
cin>>variable1>>variable2>>…>>variableN;
cout<< item1 << item2 <<…<<itemN;
7
Notes on >>




>> will cause the computer to stop the execution and look
for input data from the standard input device.
Input data are separated by white spaces and should
match the type of variable in cin list.
Spaces , newlines and tabs will be skipped.
The reading for a variable will be terminated at


a white space OR
a character that does not match the destination type.
int code;
cin >> code;
C:>text.exe
C:>4258D
Result:
code: 4258
‘D’ remains in the input stream and will be input
to the next cin statement.
8
put() and get()

get()/put(): member of istream/ostream
int get();
istream& get (char& c);
ostream& put (char c);

Using :
cin.get(ch)
--assign the input to its argument
ch=cin.get(void)
--returns the input character
put(ch)
--display the value of ch.
9
put() and get()

Example:
int main(){
char c;
cin.get(c);
while (c != '\n')
{
cout << c;
cin.get(c);
}
}
//replace cin.get(c) with cin >> c and compare
the result.
10
put() and get()

Example:
cout.put(68)  ’D’
Example-code: (program 10.1)
cin.get(c);
while(c != ‘\n’)
{
cout.put(c);
cin.get(c);
}
The text is sent to the program as soon as we press the RETURN key.
The program then reads and displays characters one by one.
the process is terminated when the newline character is
encountered.
11
getline()




cin.getline(line, size)
reads character input into the variable line.
the reading is terminated as soon as either ‘\n’ is
encountered or size-1 characters are read.
the newline character ‘\n’ is read but not saved.
Instead, it is replaced by the null character.
12
Example of getline()
Example-code: (program 10.2)
int main() {
int size = 20;
char city[20];
cout << "Enter city name: \n";
cin.getline(city,
size);
cin >> city;
cout << "City name: " << city <<"!\n\n";
cout << "Enter city name again: \n";
cin.getline(city,size);
cout << "City name now: " << city <<“!\n\n";
cout << "Enter another city name: \n";
cin.getline(city,size);
cout << "New city name: " << city << “!\n\n";
return 0;
}
13
write()





cout.write(line, size)
displays an entire line
line: the string to be displayed
size: the number of character to display
Note: it does not stop automatically at the null
character

If the size is greater than the length of line, then it
displays beyond the bounds of line.
Example of write()
Example-code: (program 10.3)
int main(){
char * string1 = "C++ ";
char * string2 = "Programing";
int m = strlen(string1);
int n = strlen(string2);
for (int i=1; i<n; i++){
cout.write(string2,i);
cout << "\n";
}
for(int i=n; i>0; i--){
cout.write(string2,i); cout << "\n";
}
//concotenating strings
cout.write(string1,m).write(string2,n);
cout << "\n";
//crossing the boundary
cout.write(string1,10); cout << "\n";
}
§10.3 Formatted Console I/O Operation

To format the output:




ios class functions and flags
Manipulators
User-defined output functions
ios format functions
Function
Description
width()
To specify the required filed size for displaying an output value
precision() To specify the number of digits to be displayed after the decimal
point of a float value
fill()
To specify a character to fill the unused portion of a field
setf()
To specify format flags that can control the form of output
display (i.e. left-/right-justification)
unsetf()
To clear the format flags specified
16
Defining Field Width: width()
cout.width(w);
The output will be printed in a field of w characters wide
--At the right end of the field
--Can control only the following one item
--Will be expanded automatically if w is smaller than the
size of the value to be put
cout.width(5);
cout << 543 << 12 << "\n";
5
4
3
cout.width(5);
cout << 543 ;
cout.width(5);
cout << 12 << "\n";
5
4
3
1
Program 10.4
2
1
2
17
Setting precision: precision()

To specify the number of digits to be displayed
after the decimal point

6 digits after the decimal point, by default
cout.precision(d)
--d is the number of digits to display
--the value is rounded to the nearest cent: 1.3331.3
--trailing zeros are truncated
--Retaining effective until reset
18
Example of precision()
(example 10.5)
cout.precision(3);
cout << sqrt(2) << "\n";
cout << 3.14159 << "\n";
cout << 2.50032 << "\n";
cout.precision(2);
cout.width(5);
cout << 1.2345;
output:
1.141 (truncated)
3.142 (rounded to the nearest cent)
2.5 (no trailing zeros)
1.23 (right justisfied)
19
Filling and Padding: fill()
cout.fill(ch);
--ch is the character used to fill positions
--Retaining effective until reset
cout.fill('<');
 example : Program 10.6
cout.precision(3);
for(int n=1; n<=6; n++){
cout.width(5);
cout << n;
cout.width(10);
cout << 1.0 / float(n) << "\n";
if (n==3) cout.fill('>');
}
cout << "\nPadding changed \n\n";
cout.fill('#'); cout.width(15);
cout << 12.345678 << "\n";
20
Format Flags, Bit-field and setf()
cout.setf(flag, bit-field);
--to set format flags
--flag: the flag to be set
--bit-field: the group of the flag (bit-field)
Flag
left
fight
internal
dec
oct
hex
Scientific
fixed
Bit-field
Format
Left justified
Right justified
adjustfield
Padding after sign or base Indicator
(e.g. +##20)
Decimal base
basefield Octal base
Hexadecimal base
Scientific notation
floatfield
Fixed point notation
21
Example of setf(arg1, arg2)
cout.fill('*');
cout.setf(ios::left, ios::adjustfield);
cout.width(15);
T A B L
cout << "TABLE 1" << "\n";
E
cout.fill('*');
cout.precision(3);
cout.setf(ios::internal, ios::adjustfield);
cout.setf(ios::scientific, ios::floatfield);
cout.width(15);
- * * * *
cout << -12.34567 << "\n";
*
1 *
*
*
*
*
*
*
1 .
2 3 5 e + 0 1
22
*
Displaying Trailing Zeros and Plus Sign

To print 10.75, 25.00 and 15.50 using a field width of 8
positions, with 2 digits precision:
1

0
.
7
5
2
5
1
5
.
5
1
0
.
7
5
2
5
.
0
0
1
5
.
5
0
How to show:
23
Displaying Trailing Zeros and Plus Sign
setf(arg)
arg: independent flag
cout.setf(ios::showpos); //show + sign
cout.setf(ios::showpoint); //displaying trailing zeros
Flag
Meaning
ios::showbase
ios::showps
ios::showpoint
ios::uppercase
ios::skipus
ios::unitbuf
ios::stdio
Use base indicator on output
Print + before positive numbers
Show trailing decimal point and zeroes
Use uppercase letters for hex output
Skip white space on input
Flush all streams after insertion
Flush stdout and stderr after insertion
24
Example of setf(arg)

Program 10.7
cout.setf(ios::showpoint);
cout.setf(ios::showpos);
cout.precision(3);
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::internal, ios::adjustfield);
cout.width(10);
cout << 275.5 << "\n";
+
2
7
5
.
5
0
0
25
§10.4 Output with Manipulators

Manipulators



Also functions to format output
Special: can be included in the I/O statements
Defined in header file iomanip
Manipulators
Equivalent functions
setw()
setprecision()
setfill()
setiosflags()
resetiosflags()
width()
precision()
fill()
setf()
unsetf()
cout << manip1 << manip2 << manip3 <<item;
cout << manip1 << item1 << manip2 << item2;
26
Example of Manipulators

Program 10.8
cout << setw(10) << 12345;
cout << setw(10) << setiosflags(ios::left) << 12345;
cout << setw(5) << setprecision(2) << 1.2345
<< setw(10) << setprecision(4) << sqrt(2)
<< setw(15) << setiosflags(ios::scientficif) << sqrt(3);
<< endl;
//print all the three values in one line with different sizes
27
Defining Our Own Manipulators
ostream & manip_name (ostream & output)
{
//to be added
return ouput;
}
ostream & unit(ostream &
ouput)
{
output << " inches";
return output;
}
cout << 36 <<unit ;
//will produce "36 inches"
ostream & show(ostream & output)
{
output.setf(ios::showpoint);
output.setf(ios::showpos);
output << setw(10);
return output;
}
28
A Summary


Concepts of stream, stream classes
Unformatted input and output


>>, <<, cin, cout, get, put, getline, write
Formatting output

Format functions


width, precision, setf, etc.
Manipulators


Standard from C++ library
Defined by user
Review Questions

Null.