You are on page 1of 29

INPUT AND

OUTPUT
UCCD1004 Programming Concepts and Practices
Content Overview
Structure of C++ Programs

Statements Control Control


String and
and Structures Structures Functions Structs Pointers
Array
Expressions (Selection) (Iteration)

Input & Pass-by-


Data Types FileIO Classes
Output reference
Introduction

• Program performs 3 basic operations: input, process and output.

• IO can be very complex.


• Keyboard
• Network
• Disk
• Sensors
IO Stream

• A stream is a sequence of characters from the source to the


destination. There are 2 types of streams:-

• Input Stream: incoming stream

• Output Stream: outgoing stream


The extraction operator >>

• cin >> payRate

• It inputs the next number typed on the keyboard and stores that
number in payRate.

• The extraction operator takes two operands, from cin (input


stream variable) and store the value in a variable (e.g. payRate)
The extraction operator >>

• We can also use multiple >>. For example:-


cin >> a >> b

• It is equivalent to
cin >> a;
cin >> b;
The extraction operator >>
cout, <<, and endl.

• These are use to print the content of our variables to the


monitor.

• endl is meant for displaying newline.


Formatting output

• setprecision(n)

#include <iomanip>
cout << setprecision(2) << 3.142;

What is the output?


Output will be 3.1
Formatting output

• cout << showpoint; sets the output of decimal numbers


with a decimal point and trailing zeros

• cout << fixed << showpoint; Fixed decimal format


with the decimal point and trailing zeros.
Formatting output
cout << setw(5) << w << endl;

• The manipulator setw is used to output the value of an expression in a


specific number of columns.

• The value of the expression can be either a string or a number. The


expression setw(n) outputs the value of the next expression in n columns.

• The output is right justified.


For example

cout << setprecision(2) << 1.235 << endl; //1.2


cout << setprecision(4) << 1.235 << endl; //1.235
cout << setprecision(6) << 1.235 << endl; //1.235
        
cout << showpoint;
cout << setprecision(6) << 1.235 << endl; //1.23500
        
cout << fixed << showpoint;
cout << setprecision(6) << 1.235 << endl; //1.235000
Another example
cout << showpoint;
cout << 123458.256 << endl;
cout << 1.2345256 << endl;
cout << 1.23 << endl;
        
cout << setprecision(5) << 1.23 << endl;
cout << setprecision(3) << 1.235 << endl;
cout << setprecision(2) << 123.235 << endl;
cout << setprecision(6) << 12345.256 << endl;
        
cout << fixed << showpoint;
cout << 12345.256 << endl;
cout << setprecision(6) << 1.235 << endl;
Using Files Stream objects
1. Include the fstream header file.
2. Use of files requires fstream header file. TWO types of file
stream objects. Define a file stream object.
– use ifstream connect to input files. Open existing input files
and read data from them into memory. (Read)
– use ofstream connect to output files. Open output files and
write data to them. (Write/save)
3. Define ofstream and ifstream objects
ifstream inFile;
ofstream outFile;
Default File Open Modes
ifstream ofstream
Open for input only (Read in) Open for output only (Write Out)
File cannot be written to File cannot be read from
Open fails if file does not exist File creates if no file exists; file contents
erase if file exists and flag is not defined
ifstream inFile; ofstream outFile;
inFile.open(“c:\\inventory.dat"); outFile.open("report.txt");
Or Or
fstream inFile; fstream outFile;
inFile.open(“c:\\inventory.dat“, ios::in); outFile.open("report.txt“, ios::out);
Use the File

ifstream ofstream
Can use input file object and >> to copy Can use output file object and << to write
data from file to variables data to a file

inFile >> partNum; outFile << "Inventory report";


inFile >> qtyInStock >> qtyOnOrder;

Similar to cin >> Similar to cout <<

3-16
Flags of fstream
ifstream inFile;
ofstream outFile;
Flag Description Example
ios::in Open for input operations; inFile.open
default operation of ifstream. ("example.txt",ios::in);

ios::out Open for output operations; outFile.open


default operation of ofstream. ("example.txt",ios::out);
ios::ate Set the initial position at the end of outFile.open
the file; ("example.txt",ios::ate);
If this flag is not set, the initial
position is the beginning of the file.
Flags of fstream (cont.)
ifstream inFile;
ofstream outFile;
Flag Description Example
ios::app All the output operations are outFile.open
performed at the end of the file, ("example.txt",ios::app);
the content is continue to the
current content of the file
ios::trunc If the existing file is opened for outFile.open
output operation, its existing ("example.txt",ios::trunc
content will be replaced with the );
new content.
File Input and Output
Write file example
#include <iostream>
#include <fstream> Step 1 Define header file
using namespace std;
int main ()
{
ofstream myfile; Step 2 Declare file stream variable
myfile.open ("example1.txt"); Step 3 Associates with sources
myfile << "Writing this to a file.\n"; Step 4 User << or >> to read in
myfile.close(); Step 5 Close the file or write out

return 0;
}
To append to a file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt",ios::app);
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Member Functions for Reading and Writing Files
• Unlike the extraction operator >>, these reading functions do not skip
whitespace:
– getline: reads input including whitespace
string line;
getline (myfile,line)

– get: reads a single character from a file


char letterGrade;
myfile.get(letterGrade);

– put: writes a single character to a file


myfile.put(letterGrade);
Read file example (string)
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std; continue to read lines
int main () while it is not the last
{ line
string line;
ifstream myfile ("example.txt");
if (myfile.is_open()) 321rdndst
{ Iteration
Iteration
Iteration
when while ( getline (myfile,line) )
“example.txt {
” cout << line << '\n';
exist }
myfile.close();
and
}
open else
cout << "Unable to open file";
return 0;
}
Read file example (figures)
int main(){
ifstream inFile;
inFile.open("even.txt");
check whether the file exists in the folder or not
int evenNumber, amount=0;
if (inFile.fail())
cout << "Unable to open the file! " << endl;
else {
8231thnd
rdst
Iteration
Iteration 2 4 6 16
while (!inFile.eof()) {
inFile >> evenNumber;
cout << evenNumber << " ";
While it is not
the end of the file,amount+;
continue to read }
cout << endl;
}
cout << "The total of even numbers is " << amount << endl;
inFile.close();
system("pause");
return 0;
}
Read file example (mix)
ifstream inFile;
inFile.open("mix.txt");
int height, weight, amount=0;
string name, gender;
if (inFile.fail()) 1. Name
cout << "Unable to open the file! " << endl;
2. Height 3. Weight 1st Person
else {
4. Gender 1st Iteration
while (!inFile.eof()) {
cout << "Person " << amount+1 << endl;
getline(inFile, name);
2nd Person
Tey
SasTey
Ang
cout << "Name: " << name << endl; AngTey
Sas Ang 2nd Iteration
162
164
178
inFile >> height >> weight; 45
67
56
cout << "Height: " << height << endl; 312rd
nd
st
Person
Person
cout << "Weight: " << weight << endl; 312rd
nd
st Iteration
Iteration
Iteration 3rd Person
inFile.ignore(); 3rd Iteration
getline(inFile, gender);
female
female
male
cout << "Gender: " << gender << endl;
cout << endl;
amount++;
}
}
inFile.close();
Important Tips

1. Understand the pattern of your text file


– Study the pattern of the files before read in
2. Read in the text according to the patterns
3. Design carefully when write out
Close the File
Use the close member function
inFile.close();
outFile.close();

• Don’t wait for operating system to close files at program end


– May be limit on number of open files
– May be buffered output data waiting to be sent to a file that
could be lost

3-28
Common issue with read and write files

• Make sure to close the file after using.


• Make sure the path is correct.
• Make sure your program have the access rights to the files.

You might also like