Chapter 10 Console I/O Operations

Preview:

DESCRIPTION

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

Citation preview

Chapter 10Console 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

2

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).

3

§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

InputdeviceInput

device

OutputdeviceOutputdevice

ProgramProgramOutput streamOutput stream

Input streamInput streamExtractExtract

InsertInsert

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

iosios

ostreamostreamistreamistreamstreambufstreambuf

iostreamiostream

istream_withassignistream_withassign ostream_withassignostream_withassigniostream_withassigniostream_withassign

cincin coutcout

get(), read(), getline()overloading <<

put(), write()overloading >>

§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:

7

cin>>variable1>>variable2>>…>>variableN;

cout<< item1 << item2 <<…<<itemN;

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.

8

int code;cin >> code;

C:>text.exeC:>4258D

Result:code: 4258‘D’ remains in the input stream and will be input to the next cin statement.

put() and get() get()/put(): member of istream/ostream

Using :

9

cin.get(ch) --assign the input to its argumentch=cin.get(void) --returns the input characterput(ch) --display the value of ch.

int get(); istream& get (char& c); ostream& put (char c);

put() and get() Example:

10

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.

put() and get() Example:

11

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.

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()

13

Example-code: (program 10.2)

int main() { int size = 20; char city[20]; cout << "Enter city name: \n"; 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;}

cin.getline(city, size);

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 stringscout.write(string1,m).write(string2,n);cout << "\n";//crossing the boundarycout.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

16

Function Descriptionwidth() To specify the required filed size for displaying an output valueprecision() To specify the number of digits to be displayed after the decimal

point of a float valuefill() To specify a character to fill the unused portion of a fieldsetf() To specify format flags that can control the form of output

display (i.e. left-/right-justification)unsetf() To clear the format flags specified

Defining Field Width: width()

17

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";

cout.width(5);cout << 543 ;cout.width(5);cout << 12 << "\n"; Program 10.4

5 4 3 1 2

5 4 3 1 2

Setting precision: precision()

To specify the number of digits to be displayed after the decimal point 6 digits after the decimal point, by default

18

cout.precision(d)--d is the number of digits to display--the value is rounded to the nearest cent: 1.3331.3--trailing zeros are truncated--Retaining effective until reset

Example of precision()

(example 10.5)

19

cout.precision(3);cout << sqrt(2) << "\n";cout << 3.14159 << "\n";cout << 2.50032 << "\n";

output:1.141 (truncated)3.142 (rounded to the nearest cent)2.5 (no trailing zeros)

1.23 (right justisfied)cout.precision(2);cout.width(5);cout << 1.2345;

Filling and Padding: fill()

example : Program 10.6

20

cout.fill(ch);--ch is the character used to fill positions--Retaining effective until reset

cout.fill('<');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";

Format Flags, Bit-field and setf()

21

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 Bit-field Format

leftfightinternal

adjustfield

Left justifiedRight justifiedPadding after sign or base Indicator (e.g. +##20)

decocthex

basefieldDecimal baseOctal baseHexadecimal base

Scientificfixed

floatfieldScientific notationFixed point notation

Example of setf(arg1, arg2)

22

cout.fill('*');cout.setf(ios::left, ios::adjustfield);cout.width(15);cout << "TABLE 1" << "\n";

cout.fill('*');cout.precision(3);cout.setf(ios::internal, ios::adjustfield);cout.setf(ios::scientific, ios::floatfield);cout.width(15);cout << -12.34567 << "\n";

T A B L E 1 * * * * * * * *

- * * * * * 1 . 2 3 5 e + 0 1

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:

How to show:

23

1 0 . 7 5

2 5

1 5 . 5

1 0 . 7 5

2 5 . 0 0

1 5 . 5 0

Displaying Trailing Zeros and Plus Sign

24

setf(arg)arg: independent flag

cout.setf(ios::showpoint); //displaying trailing zeroscout.setf(ios::showpos); //show + sign

Flag Meaning

ios::showbaseios::showpsios::showpointios::uppercaseios::skipusios::unitbufios::stdio

Use base indicator on outputPrint + before positive numbersShow trailing decimal point and zeroesUse uppercase letters for hex outputSkip white space on inputFlush all streams after insertionFlush stdout and stderr after insertion

Example of setf(arg)

Program 10.7

25

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

§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

26

cout << manip1 << manip2 << manip3 <<item;cout << manip1 << item1 << manip2 << item2;

Manipulators Equivalent functions

setw()setprecision()setfill()setiosflags()resetiosflags()

width()precision()fill()setf()unsetf()

Example of Manipulators

Program 10.8

27

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

Defining Our Own Manipulators

28

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;}

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.

Recommended