Вы находитесь на странице: 1из 21

Computer Programming

7. Stream I/O

Input and Output

I/O implementation is hardware dependent

C++ does not, as a part of the language, define


how data are sent out and read into the program
The input and output (I/O) are handled by the
standard C++ library (such as iostream)

A library is a collection of object code to be linked to the


C++ program to provide additional functionality

For different platforms, different libraries (that may use


the same name) can be used for I/O functions

This allows the C++ program to be less platform


dependent

It is because I/O is usually quite different from


computers to computers.
1

Computer Programming
7. Stream I/O

Standard I/O Objects


When a C++ program that includes the iostream
classes starts, four objects are created and
initialized

cin - handle input from the standard input, i.e.


keyboard

cout - handle output to the standard output, i.e.


display

cerr - handle unbuffered output to the standard error


device, i.e. display in a PC

clog - handle buffered error messages that are


output to the standard error device, i.e. display in a PC.

Buffered: Display only when a flush command is received, e.g. endl statement
2

Computer Programming
7. Stream I/O

Keyboard and Screen I/O


#include<iostream>
output data

input data
executing
program

Keyboard

cin

Screen

cout

(of type istream)

(of type ostream)

Computer Programming
7. Stream I/O

Output: Buffer to output device


Input: Buffer to computer program

Buffering

iostream classes view the flow of data as being


a stream of data, one byte following another
Buffer is provided in some cases to the stream
The stream of data does not send out if the buffer is
not full or no flush request is received
It is useful in some situations such as written data to
disk since the overhead is very large. It is better to
do it in single lots rather than byte by byte.

Program

Data Stream

Buffer

Temporary Memory

Hard disk
I/O
4

Computer Programming
7. Stream I/O

>>isabinaryoperator
>>iscalledtheinputorextractionoperator
>>isleftassociative
EXPRESSION

RETURNSVALUE

cin>>age

cin

STATEMENT

cin>>age>>weight;
5

Computer Programming
7. Stream I/O

char xyz[10];
cin >> xyz;

Program

Keyboard
Chan

xyz =
"Chan"

Chan
Buffer:
Memory in
your keyboard
6

Computer Programming
7. Stream I/O

NOTE:
shows the location of the reading marker
STATEMENTS
CONTENTS
MARKER
POSITION
int
a;
int
b;
int
c;
cin >> a >> b ;

cin.ignore(100, \n) ;

cin >> c ;

957

34

957

34

957

34

128

957 34 1235\n
128 96\n
957 34 1235\n
128 96\n
957 34 1235\n
128 96\n
957 34 1235\n
128 96\n
7

Computer Programming
7. Stream I/O

Input using cin


cin has been generally used for input data from
keyboard
int someVariable;
cin >> someVariable;

It is a global object - doesnt need to define in our own


code
The operator >> is overloaded such that different kind
of data can be read into the buffer of cin and then to
someVariable
float someVariable1;
cin >> someVariable1;

double someVariable2;
cin >> someVariable2;

char someVariable3[100];
cin >> someVariable3;
8

Computer Programming
7. Stream I/O

Member functions of cin


InputStreamMethods

Computer Programming
7. Stream I/O

Member functions, e.g. cin.get()


As cin is an object, it has its own member
functions
Helps to obtain the input data in a more flexible way.
#include <iostream>
cin.get()
cin.get()returns
returns
using namespace std;
aa character
character from
from
int main()
standard
input
standard
input
{
char ch;
The
The loop
loop will
will stop
stop
while ((ch = cin.get()) != EOF)
if
end-of-file
{
if end-of-file
cout << "ch: " << ch << endl; (crtl-z)
(crtl-z) is
is input
input
}
cout << "\nDone!\n";
EOF:
EOF: 0xFF
0xFF
return 0;
isis aa condition
condition
}
10

Computer Programming
7. Stream I/O

Member functions of cin


Statusmethods:

11

Computer Programming
7. Stream I/O

This is the
"Enter" key (newline character)
If we press crtl-z , it
becomes End-of-file
(EOF) condition.
12

Computer Programming
7. Stream I/O

//Endoffileatkeyboard

Ctrl-D in
UNIX

total=0;
cout<<Enterbloodpressure(CtrlZtostop);
cin>>thisBP;
//primingread
while(cin)//whilelastreadsuccessful;orwhile(!cin.eof())
{
total=total+thisBP;
cout<<Enterbloodpressure;
cin>>thisBP;
//readanother
}
cout<<total;
13

Computer Programming
7. Stream I/O

Member functions, e.g.


cin.getline()
cin.getline() allows the whole line of data to be
input to a string
Include NULL, i.e. '\0'
cin.getline(buffer, MAXSIZE);

at the end

The maximum length of data to be read is defined by


MAXSIZE
Unlike cin, getline() will read in the terminating
newline character and throw it away
With cin, the terminating newline is not thrown away,
but left in the input buffer.
cin will neglect ,though, any preceding space, tab and newline
14

Computer Programming
7. Stream I/O

Why do we use cin.getline()?


cin >> abc has been used quite often since
the redirection operator >> is overloaded, i.e.

such statement can be used no matter abc is a


string, an integer or a floating-point number

However if abc is a string, cin >> abc allows


only string with continuous characters input

cin >> abc will stop to read in data if it sees, e.g. a


space

cin.getline() is different in that getline() can


only read in string, but not other data types;
however, it will not stop when encountering
spaces or tabs.
15

Computer Programming
7. Stream I/O

#include <iostream>
using namespace std;
int main()
{ char stringOne[256];
char stringTwo[256];
char stringThree[256];
cout << "Enter string one: ";
cin.getline(stringOne,256);
cout << "stringOne: " << stringOne << endl;

Notice the space

The >>
>> operator
operator reads
reads until
until aa
cout << "Enter string two: "; The
new-line
cin >> stringTwo;
new-line or
or aa space
space character
character
cout << "stringTwo: "
is
is seen.
seen. Thats
Thats why
why five
five six
six
<< stringTwo << endl;
are
are read
read to
to stringThree[]
stringThree[]
cout << "Enter string three: ";
cin.getline(stringThree,256);
cout << "stringThree: " << stringThree << endl;
return 0;
}

16

Computer Programming
7. Stream I/O

char abc[10], xyz[10];


cin >> abc; cout << "abc: "
cin.getline(xyz,10);
cout << "xyz: " << xyz << endl;

<< abc << endl;

Program

Keyboard
Chan

abc =
"Chan\0"
xyz ='\0'

Chan

and then
buffer clear

Buffer :
Memory in
your
keyboard

The "Enter"
code is still in
the buffer
17

Computer Programming
7. Stream I/O

char abc[10], xyz[10];


cin.getline(abc,10);cout << "abc: " << abc << endl;
cin.getline(xyz,10);
cout << "xyz: " << xyz << endl;

Program

Keyboard
Chan

abc =
"Chan\0"

Chan
Buffer :
Memory in your
keyboard

The "Enter"
key has been
cleared
18

Computer Programming
7. Stream I/O

Output with cout


Just as cin, cout is also an object created when
the iostream class starts
cout represents the standard output, i.e. display
The operator << is overloaded such that different kind of
data can be sent out

Similar to cin, cout also has a number of


member functions
cout.put(char a)

You may write cout.put(a)<<endl;

Put the value of character a to output, and return cout


cout.write(char *buf, int length)

Not including NULL

Write length characters in buf to output device , and


return cout.
19

Computer Programming
7. Stream I/O

#include <iostream>
#include <string>
using namespace std;
int main()
{
char One[] = "One if by land";
int fullLength = strlen(One);
int tooShort = fullLength - 4;
int tooLong = fullLength + 6;

write()
write()asks
asks the
the
system
system to
to write
write
tooLong
tooLong characters.
characters.
Hence
Hence something
something
unexpected
unexpected is
is displayed
displayed

cout.write(One,fullLength) << "\n";


// fullLength=14,return cout after write
cout.write(One,tooShort) << "\n";
cout.write(One,tooLong) << "\n";
return 0;
}
20

Computer Programming
7. Stream I/O

Other Member Functions


cout.width(int a)
Set the width of the next output field to a's value
cout.fill(char a)
Fill the empty field of the output by a's value
#include
<iostream>
return
cout.
using namespace std;
int main()
{
cout << "Start >";
cout.width(6);
cout << 123 << "<End\n";

width(6)
width(6) defines
defines the
the total
total
width
width of
of the
the field
field to
to be
be 66
char.
char.
fill('*')
fill('*') fills
fills the
the empty
empty
field
field with
with **

cout << "Start >";


cout.width(6);
cout.fill('*');
cout << 123 << "<End\n";
return 0;
}

21

Computer Programming
7. Stream I/O

Formatting numbers for program output


ostream Class Methods

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
22

Computer Programming
7. Stream I/O

Exercise 7.1
Write a program that asks the user to
1. Input his/her surname

Input in TWO lines

2. Input his/her first name

First name can be 1 word or 2 words

If the user puts a space between the two words of his first
name, add a hyphen to replace the space. Skip all other
spaces in front of or after the first name or surname.
For example:

Chan
Tai Ming

Chan Tai-Ming

Show the whole name after you read the user inputs.
Hint: A string is a character array. You can use a loop to
check the content of every character of a string one by one,
and to display the characters out one by one.
23

Computer Programming
7. Stream I/O

File Input and Output

Text file

C++ provides library functions to help us deal with


file accesses
File access is usually performed in the following
way:
To claim from the system the
Open
Open file
file

Read
Read data
data
from
from file
file

Write
Write data
data
to
file
to file

Close
Close file
file

access of a particular file

To perform the read or write


instructions
To indicate to the system the file
access is finished (closed)

It is not guaranteed that data can be


written to file if not closing.
24

Computer Programming
7. Stream I/O

File I/O Using Streams

Unlike cin, we can have more


than one file being processed in
a program.

Streams provide a uniform way of dealing with


data sending to or reading from files

Classes The objects that are used to deal with files are called
ofstream and ifstream objects
To create an ofstream or ifstream object, we need
to include fstream (header file) in our program
To open a file for write or read, first create an
ofstream or ifstream object with the filename as
the input parameter.
fout and fin are objects but
ofstream fout("myfile.cpp"); NOT standard objects, unlike
ifstream fin("myfile.cpp");
cout and cin. Any other
names are O.K.
25

Computer Programming
7. Stream I/O

Diskette Files for I/O


#include<fstream>
input data

output data

disk file
C:\myInfile.dat

executing
program

your variable
(of type ifstream)

disk file
C:\myOut.dat

your variable
(of type ofstream)
26

Computer Programming
7. Stream I/O

StatementsforusingDiskI/O
#include<fstream>
ifstreammyInfile;

//declarations

ofstreammyOutfile;
myInfile.open(C:\\myIn.dat);
myOutfile.open(C:\\myOut.dat);
myInfile.close();
myOutfile.close();

//openfiles

//closefiles
27

Computer Programming
7. Stream I/O

Opening a file
y associatestheC++identifierforyourfilewiththe
physical(disk)nameforthefile
y iftheinputfiledoesnotexistondisk,openisnot
successful
y iftheoutputfiledoesnotexistondisk,anewfile
withthatnameiscreated
y iftheoutputfilealreadyexists,itiserased
y placesafilereadingmarker attheverybeginningof
thefile,pointingtothefirstcharacterinit
28

Computer Programming
7. Stream I/O

Read or Write Files

After opening files, reading or writing files can be


done in a similar way as cout or cin

After writing/reading, the file should be closed by the


member function close() of the ofstream/ifstream
objects.
#include <iostream>
To see the output, look at the
using namespace std;
content of the file myfile.cpp
#include <fstream>
int main() {
If
If for
for any
any reason
reason
ofstream fout("myfile.cpp");
myfile.cpp
cannot
myfile.cpp
cannot be
be
fout << "This line is written to file.\n";
opened,
fout.close();
opened, fout
fout && fin
finwill
will
ifstream fin("myfile.cpp");
still
still be
be created,
created, but
but
char ch;
fout.fail()
return
fout.fail() return true.
true.
while (fin.get(ch)) //NULL if end of file
cout << ch;
fin.close();
Similar
Similar to
to cout
cout and
and cin.get(ch).
cin.get(ch).
return 0;
}
29

Computer Programming
7. Stream I/O

Reading Character-Based Files


y Usean ifstream objecttoreaddatafromatextfile
Syntax:
inputFileStream >> variableName

y Theeof() methodcanbeusedtotestiftheendof
filehasbeenreached
Example:
//while not at end of file
while(!inFile.eof())
30

Computer Programming
7. Stream I/O

Reading 20 Books from file


C:\\book.dat

Hardback or
Paperback?

Price of book
3.98 P <eoln>
7.41 H <eoln>
8.79 P <eoln>
.
.
.

WRITE A PROGRAM TO FIND TOTAL VALUE OF ALL BOOKS

31

Computer Programming
7. Stream I/O

#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
float
char
int
ifstream

// for cout
// for file I/O

price, total = 0.0 ;


kind ;
count = 1;
myInfile (C:\\book.dat);

// declarations

// myInfile.open(C:\\book.dat) ;

while ( count < 21 )


{
myInfile >> price >> kind ;
total = total + price ;
count ++ ;
}
cout << Total is: << total << endl ;
myInfile.close( ) ;
return 0 ;
}

32

Counting Frequency of Alphabetic Characters


//Programcountsfrequencyofeachalphabeticcharacterinatextfile.
#include<fstream>
#include<iostream>
usingnamespacestd;
int main(){
ifstream dataFile ;
int
freqCount [26]={0};
charch,index;

//zerooutthearray

dataFile.open (C:\\my.dat );
//openandverifysuccess
if(!dataFile ) {
cout << CANTOPENINPUTFILE! <<endl;
return1;
}

dataFile.get (ch );
//readfileonecharacteratatime
while(dataFile ){
//whilelastreadwassuccessful
if(ch >=A &&ch <=Z ))++freqCount [ch A ];
dataFile.get(ch );
//getnextcharacter
}

return0;

33

Computer Programming
7. Stream I/O

Changing Default Behavior

Default behavior of opening a file (by ofstream) is


to create it if it doesnt yet exist
If exists, it deletes all its contents and overwrite on it
ofstream fout2("myfile.cpp",ios::app);
(truncate)
This default behavior can be changed by providing a
second parameter to the constructor

No effect ios::app File will be opened for appending data to the


to input
end of the existing file
Open modes of class ios
Still truncate ios::ate Place you at the end of the file (either input or
output), but write data at the current position, like trunc
for output

ios::trunc Default for ofstream; truncates if it exists


Overwrite

ios::in The file (if it exists) will NOT be truncated, the


read/write cursor is positioned at the start of the file.
ios::ate|ios::in is similar to ios::app

34

Computer Programming
7. Stream I/O

Writing to Files
y Generalform
object_name<<variable_name;
y Useofstream objecttowritetofilelikecout
wasused
ofstream outfile(C:\\salary.out,ios::app);
outfile <<Salaryforweekwas <<money;
y Additionalwritingappendedtofile
35

Computer Programming
7. Stream I/O

Appending to the End of File


#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream fout("myfile.cpp"); //Default trunc
fout << "This line is written to file.\n";
fout.close();
File
File name
name can
can be
be
char fname[]="myfile.cpp";
supplied
by
a
variable
ofstream fout2(fname,ios::app);
supplied by a variable
fout2 <<
"This line is appended to the end of the previous line\n";
fout2.close();
The default
default behavior
behavior is
is changed
changed
ifstream fin("myfile.cpp"); The
char ch;
while (fin.get(ch)) To
To avoid
avoid redefining
redefining variable,
variable, aa
cout << ch;
different
different name
name should
should be
be provided
provided
fin.close();
even
for
opening
the
same
even for opening the same file
file
return 0;}
36

36

Computer Programming
7. Stream I/O

M
//Assume myfile.cpp contains "This line is written to file.\n"

ofstream fout2("myfile.cpp", ios::in);


fout2 << "Beginning of file";
fout2.close();

Default
Defaultbehavior
behaviorisischanged
changedtotonon-truncate.
non-truncate.The
Theline
line
will
willreplace
replacethe
thebeginning
beginningpart
partofofthe
thetext
textininthe
thefile;
file;but
but
the
therest
restwords,
words,ififany,
any,will
willbe
beleft
leftininthe
thefile.
file.

ifstream fin("myfile.cpp");
if (!fin) {cout << "File opening error!\n"; return 0;}
//The operator ! is defined for stream object, if the stream is
bad, return false (NULL)

It
It is
is aa good
good practice
practice to
to
check
check ifif anything
anything goes
goes
wrong
wrong when
when opening
opening aa file
file

char ch;
while (fin.get(ch))
cout << ch;
fin.close();
return 0;
M

37

Computer Programming
7. Stream I/O

Editing File

seekp has NO effect to ios::app

It is often that we need to modify a particular


part of a file - editing a file
ofstream and ifstream offers 4 member functions
that set the current position of an opened file

For ofstream
seekp(long pos);
tellp();

For ifstream
seekg(long pos);
tellg();

The first position is position 0.


seekp
seekp sets
sets the
the current
current position.
position. pos
pos is
is
aa byte
offset
from
the
file
beginning
byte offset from the file beginning
tellp
tellp tells
tells the
the current
current position.
position. Return
Return
aa byte
byte offset
offset from
from the
the file
file beginning
beginning
seekg
seekg and
and tellg
tellg are
are similar
similar to
to seekp
seekp
and
and tellp
tellp except
except they
they are
are for
for
ifstream
ifstream
38

Computer Programming
7. Stream I/O

#include <fstream>
Change
Change the
the current
current
#include <iostream>
position
to
10
position
to
10
using namespace std;
int main()
{ ofstream test1file("test1");
cout << "Text written: \n";
cout << "This text is written to file!\n"; //write to screen
test1file << "This text is written to file!\n";
test1file.close();
Tell
Tell the
the current
current position
position
ifstream tin("test1");
tin.seekg(10);
cout << "\nCurrent position: " << tin.tellg() << "\n";
cout << "\nContent of the file after an offset of 10:\n";
char ch;
while (tin.get(ch))
{
cout << ch;
} //display file
tin.close();
return 0;
}
39

Computer Programming
7. Stream I/O

y Twotypesoffileaccess:
y Sequentialaccess:charactersarestoredandretrievedina

sequentialmanner
y Randomaccess:characterscanbereadorwrittendirectlyatany
position
y Forrandomaccess,theifstream objectcreatesalongintegerfile

positionmarkerrepresentingtheoffsetfromthebeginningofthefile
FilePositionMarkerFunctions

40

Computer Programming
7. Stream I/O

Random File Access


y seekg()/seekp() functionsallowyoutomoveto

anypositioninthefile
y Characterpositioninadatafileiszerorelative
y Argumentstoseekg()/seekp() functionsarethe
offsetintothefileandthemode(wheretheoffsetis
tobecalculatedfrom)
y Modealternatives:
y

ios::beg:startfrombeginningoffile
y ios::cur:startfromcurrentposition
y ios::end:startfromendoffile
41

Computer Programming
7. Stream I/O

Exercise 7.2
1. Build the program in the last page
2. Run the program in Command Prompt
3. Use the DOS command "dir" to find the file
"test1" and display it by using the DOS
command "type test1". Can you find the
statement as shown in the program?
4. Use seekp such that the word "written" in
the file is replaced by "*******".
5. Verify the result by using the DOS
commands "dir" and "type test1" again.
42

Вам также может понравиться