Input and Output
Input and Output
Input and Output
7. Stream I/O
Computer Programming
7. Stream I/O
Buffered: Display only when a flush command is received, e.g. endl statement
2
Computer Programming
7. Stream I/O
input data
executing
program
Keyboard
cin
Screen
cout
Computer Programming
7. Stream I/O
Buffering
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
double someVariable2;
cin >> someVariable2;
char someVariable3[100];
cin >> someVariable3;
8
Computer Programming
7. Stream I/O
Computer Programming
7. Stream I/O
Computer Programming
7. Stream I/O
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
at the end
Computer Programming
7. Stream I/O
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;
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
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
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
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
Computer Programming
7. Stream I/O
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 **
21
Computer Programming
7. Stream I/O
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
22
Computer Programming
7. Stream I/O
Exercise 7.1
Write a program that asks the user to
1. Input his/her surname
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
Text file
Read
Read data
data
from
from file
file
Write
Write data
data
to
file
to file
Close
Close file
file
Computer Programming
7. Stream I/O
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
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
Computer Programming
7. Stream I/O
y Theeof() methodcanbeusedtotestiftheendof
filehasbeenreached
Example:
//while not at end of file
while(!inFile.eof())
30
Computer Programming
7. Stream I/O
Hardback or
Paperback?
Price of book
3.98 P <eoln>
7.41 H <eoln>
8.79 P <eoln>
.
.
.
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
// declarations
// myInfile.open(C:\\book.dat) ;
32
//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
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
36
Computer Programming
7. Stream I/O
M
//Assume myfile.cpp contains "This line is written to file.\n"
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
For ofstream
seekp(long pos);
tellp();
For ifstream
seekg(long pos);
tellg();
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
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