1
Input and Output • 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.
Computer Programming7. Stream I/O
I/O implementation is hardware dependent
2
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.
Computer Programming7. Stream I/O
Buffered: Display only when a flush command is received, e.g. endl statement
Keyboard and Screen I/O
#include <iostream>
cin
(of type istream)
cout
(of type ostream)
Keyboard Screenexecutingprogram
input data output data
Computer Programming7. Stream I/O
3
4
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.
BufferData Stream
Hard disk
Computer Programming7. Stream I/O
Temporary Memory I/O
Output: Buffer to output deviceInput: Buffer to computer program
Program
>> is a binary operator>> is called the input or extraction operator
>> is left associative
EXPRESSION RETURNS VALUE
cin >> age cin
STATEMENT
cin >> age >> weight ;
Computer Programming7. Stream I/O
5
6
Computer Programming7. Stream I/O
Buffer:Memory in your keyboard
char xyz[10];cin >> xyz;
Chan
Chan xyz = "Chan"
Program
Keyboard
a b c
a b c
a b c
a b c
957 34
957 34 128
957 34
NOTE: shows the location of the reading marker STATEMENTS CONTENTS MARKER
POSITION
int a ; 957 34 1235\nint b ; 128 96\nint c ;cin >> a >> b ; 957 34 1235\n
128 96\n
cin.ignore(100, ‘\n’) ; 957 34 1235\n128 96\n
cin >> c ; 957 34 1235\n128 96\n
Computer Programming7. Stream I/O
7
8
Input using cin• cin has been generally used for input data from
keyboard
• It is a global object - doesn’t 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
int someVariable;cin >> someVariable;
float someVariable1;cin >> someVariable1;
double someVariable2;cin >> someVariable2;
char someVariable3[100];cin >> someVariable3;
Computer Programming7. Stream I/O
Member functions of cinInput Stream Methods
Computer Programming7. Stream I/O
9
10
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>using namespace std;int main(){
char ch;while ((ch = cin.get()) != EOF){
cout << "ch: " << ch << endl;}cout << "\nDone!\n";return 0;
}
cin.get() returns a character from standard input
cin.get() returns a character from standard input
The loop will stop if end-of-file (crtl-z) is input
The loop will stop if end-of-file (crtl-z) is input
Computer Programming7. Stream I/O
EOF: 0xFF is a conditionEOF: 0xFF is a condition
Member functions of cinStatus methods:
Computer Programming7. Stream I/O
11
12
Computer Programming7. Stream I/O
This is the "Enter" key (new-line character)
If we press crtl-z , it becomes End-of-file (EOF) condition.
//End‐of‐file at keyboard
total = 0;
cout << “Enter blood pressure (Ctrl‐Z to stop)”;
cin >> thisBP; // priming read
while (cin) // while last read successful; or while (!cin.eof())
{
total = total + thisBP;
cout << “Enter blood pressure”;
cin >> thisBP; // read another
}
cout << total;
Ctrl-D in UNIX
Computer Programming7. Stream I/O
13
14
Member functions, e.g. cin.getline()• cin.getline() allows the whole line of data to be
input to a string
cin.getline(buffer, MAXSIZE);
• 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.
Computer Programming7. Stream I/O
Include NULL, i.e. '\0'at the end
cin will neglect ,though, any preceding space, tab and newline
15
Computer Programming7. Stream I/O
• 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.
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
16
#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;
cout << "Enter string two: ";cin >> stringTwo;cout << "stringTwo: "
<< stringTwo << endl;
cout << "Enter string three: ";cin.getline(stringThree,256);cout << "stringThree: " << stringThree << endl;return 0;
}
The >> operator reads until a new-line or a space character is seen. That’s why five six are read to stringThree[]
The >> operator reads until a new-line or a space character is seen. That’s why five six are read to stringThree[]
Computer Programming7. Stream I/O
Notice the space
17
Computer Programming7. Stream I/O
Buffer : Memory in your keyboard
char abc[10], xyz[10];cin >> abc; cout << "abc: " << abc << endl;
cin.getline(xyz,10);cout << "xyz: " << xyz << endl;
Chan
Chan abc = "Chan\0"
ProgramKeyboard
xyz ='\0'and then buffer clear
The "Enter" code is still in the buffer
18
Computer Programming7. Stream I/O
Buffer : Memory in your keyboard
char abc[10], xyz[10];cin.getline(abc,10);cout << "abc: " << abc << endl;
cin.getline(xyz,10);cout << "xyz: " << xyz << endl;
Chan
Chan abc = "Chan\0"
ProgramKeyboard
The "Enter" key has been cleared
19
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 functionscout.put(char a)
• Put the value of character a to output, and return cout
cout.write(char *buf, int length)
• Write length characters in buf to output device , andreturn cout.
Computer Programming7. Stream I/O
You may write cout.put(a)<<endl;
Not including NULL
20
#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;
cout.write(One,fullLength) << "\n";// fullLength=14,return cout after writecout.write(One,tooShort) << "\n";cout.write(One,tooLong) << "\n";return 0;
}
write() asks the system to write tooLong characters. Hence something unexpected is displayed
write() asks the system to write tooLong characters. Hence something unexpected is displayed
Computer Programming7. Stream I/O
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
• return cout.
21
Other Member Functions
#include <iostream>using namespace std;int main(){ cout << "Start >";
cout.width(6);cout << 123 << "<End\n";
cout << "Start >";cout.width(6);cout.fill('*');cout << 123 << "<End\n";return 0;
}
width(6) defines the total width of the field to be 6 char.
fill('*') fills the empty field with *
width(6) defines the total width of the field to be 6 char.
fill('*') fills the empty field with *
Computer Programming7. Stream I/O
Formatting numbers for program outputostream Class Methods
Computer Programming7. Stream I/O
22
23
Exercise 7.1Write a program that asks the user to
1. Input his/her surname
2. Input his/her first name
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.
Computer Programming7. Stream I/O
Input in TWO lines
First name can be 1 word or 2 words
24
File Input and Output• C++ provides library functions to help us deal with
file accesses
• File access is usually performed in the following way:Open fileOpen file
Close fileClose file
• To claim from the system the access of a particular file
• 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.
• To perform the read or write instructions
Computer Programming7. Stream I/O
Read data from file
Read data from file
Write data to file
Write data to file
Text file
25
• Streams provide a uniform way of dealing with data sending to or reading from files• 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.
File I/O Using Streams
ofstream fout("myfile.cpp");ifstream fin("myfile.cpp");
Computer Programming7. Stream I/O
Classes
fout and fin are objects but NOT standard objects, unlike cout and cin. Any other names are O.K.
Unlike cin, we can have more than one file being processed in a program.
Diskette Files for I/O
your variable
(of type ifstream)
your variable
(of type ofstream)
disk file“C:\myInfile.dat”
disk file“C:\myOut.dat”
executingprogram
input data output data
#include <fstream>
Computer Programming7. Stream I/O
26
Statements for using Disk I/O
#include <fstream>
ifstream myInfile; // declarations
ofstream myOutfile;
myInfile.open(“C:\\myIn.dat”); // open files
myOutfile.open(“C:\\myOut.dat”);
myInfile.close( ); // close files
myOutfile.close( );
Computer Programming7. Stream I/O
27
Opening a file
associates the C++ identifier for your file with the physical (disk) name for the file
if the input file does not exist on disk, open is not successful
if the output file does not exist on disk, a new file with that name is created
if the output file already exists, it is erased
places a file reading marker at the very beginning of the file, pointing to the first character in it
Computer Programming7. Stream I/O
28
29
• 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/ifstreamobjects.
Read or Write Files
#include <iostream>using namespace std;#include <fstream>int main() {ofstream fout("myfile.cpp");fout << "This line is written to file.\n";fout.close();ifstream fin("myfile.cpp");char ch;while (fin.get(ch)) //NULL if end of file
cout << ch;fin.close(); return 0;}
Computer Programming7. Stream I/O
If for any reason myfile.cpp cannot be opened, fout & fin will still be created, but fout.fail() return true.
If for any reason myfile.cpp cannot be opened, fout & fin will still be created, but fout.fail() return true.
To see the output, look at the content of the file myfile.cpp
Similar to cout and cin.get(ch).Similar to cout and cin.get(ch).
Reading Character-Based Files
Use an ifstream object to read data from a text file
Syntax:
inputFileStream >> variableName
The eof()method can be used to test if the end of file has been reached
Example:
//while not at end of file
while(!inFile.eof())
Computer Programming7. Stream I/O
30
Reading 20 Books from file
“C:\\book.dat”
3.98 P <eoln>7.41 H <eoln>8.79 P <eoln>
.
.
.
Price of bookHardback orPaperback?
WRITE A PROGRAM TO FIND TOTAL VALUE OF ALL BOOKS
Computer Programming7. Stream I/O
31
#include <iostream> // for cout#include <fstream> // for file I/Ousing namespace std;
int main (){
float price, total = 0.0 ; // declarationschar kind ;int count = 1;ifstream myInfile (“C:\\book.dat”); // myInfile.open(“C:\\book.dat”) ;
while ( count < 21 ) {
myInfile >> price >> kind ;total = total + price ; count ++ ;
}cout << “Total is: “ << total << endl ;myInfile.close( ) ;return 0 ;
}
Computer Programming7. Stream I/O
32
33
// Program counts frequency of each alphabetic character in a text file.#include < fstream >#include < iostream >using namespace std;
int main ( ) {ifstream dataFile ;int freqCount [26]={0} ; // zero out the arraychar ch, index;
dataFile.open ( “C:\\my.dat” ) ; // open and verify successif ( ! dataFile ) {
cout << “ CAN’T OPEN INPUT FILE ! “ << endl;return 1;
}
dataFile.get ( ch ) ; // read file one character at a timewhile ( dataFile ) { // while last read was successful
if (ch >= ‘A’ && ch <= ‘Z’ ) ) ++freqCount [ ch ‐ ’A’ ];dataFile. get ( ch ) ; // get next character
}
return 0;}
Counting Frequency of Alphabetic Characters
34
Changing Default Behavior• Default behavior of opening a file (by ofstream) is
to create it if it doesn’t yet exist• If exists, it deletes all its contents and overwrite on it
(truncate)
• This default behavior can be changed by providing a second parameter to the constructor
ios::app – File will be opened for appending data to the end of the existing file
ios::ate – Place you at the end of the file (either input or output), but write data at the current position, like trunc
ios::trunc – Default for ofstream; truncates if it exists
ios::in – The file (if it exists) will NOT be truncated, the read/write cursor is positioned at the start of the file.
Computer Programming7. Stream I/O
ofstream fout2("myfile.cpp",ios::app);
Open modes of class ios
ios::ate|ios::in is similar to ios::app
Still truncate for output
Over-write
No effect to input
Writing to Files
General form
object_name << variable_name;
Use ofstream object to write to file like coutwas used
ofstream outfile(“C:\\salary.out”, ios::app);
outfile << “Salary for week was ” << money;
Additional writing appended to file
Computer Programming7. Stream I/O
35
36
Appending to the End of File#include <fstream>#include <iostream>using namespace std;int main(){ofstream fout("myfile.cpp"); //Default truncfout << "This line is written to file.\n";fout.close();char fname[]="myfile.cpp";ofstream fout2(fname,ios::app);fout2 << "This line is appended to the end of the previous line\n";fout2.close();ifstream fin("myfile.cpp");char ch;while (fin.get(ch))cout << ch;
fin.close();return 0;}
Computer Programming7. Stream I/O
The default behavior is changedThe default behavior is changed
To avoid redefining variable, a different name should be provided even for opening the same file
To avoid redefining variable, a different name should be provided even for opening the same file
File name can be supplied by a variableFile name can be supplied by a variable
36
37
Computer Programming7. 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();
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)char ch;while (fin.get(ch))
cout << ch;
fin.close();return 0;M
Default behavior is changed to non-truncate. The line will replace the beginning part of the text in the file; but the rest words, if any, will be left in the file.
Default behavior is changed to non-truncate. The line will replace the beginning part of the text in the file; but the rest words, if any, will be left in the file.
It is a good practice to check if anything goes wrong when opening a file
It is a good practice to check if anything goes wrong when opening a file
38
Editing File• 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
seekp(long pos);tellp();
For ofstream
seekg(long pos);tellg();
For ifstream
• seekp sets the current position. pos is a byte offset from the file beginning
• tellp tells the current position. Return a byte offset from the file beginning
• seekp sets the current position. pos is a byte offset from the file beginning
• tellp tells the current position. Return a byte offset from the file beginning
• seekg and tellg are similar to seekpand tellp except they are for ifstream
• seekg and tellg are similar to seekpand tellp except they are for ifstream
Computer Programming7. Stream I/O
The first position is position 0.
seekp has NO effect to ios::app
#include <fstream>#include <iostream>using namespace std;int main(){ ofstream test1file("test1");
cout << "Text written: \n";cout << "This text is written to file!\n"; //write to screentest1file << "This text is written to file!\n";test1file.close();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 filetin.close();return 0;
}
Change the current position to 10
Change the current position to 10
Tell the current positionTell the current position
Computer Programming7. Stream I/O
39
Two types of file access:
Sequential access: characters are stored and retrieved in a sequential manner
Random access: characters can be read or written directly at any position
For random access, the ifstream object creates a long integer file position marker representing the offset from the beginning of the file
File Position Marker Functions
Computer Programming7. Stream I/O
40
Random File Accessseekg()/seekp() functions allow you to move to any position in the file
Character position in a data file is zero‐relative
Arguments to seekg()/seekp() functions are the offset into the file and the mode (where the offset is to be calculated from)
Mode alternatives:
ios::beg: start from beginning of file
ios::cur: start from current position
ios::end: start from end of file
Computer Programming7. Stream I/O
41
42
Exercise 7.21. 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.
Computer Programming7. Stream I/O