Chapter 3 Input/Output
Download
Report
Transcript Chapter 3 Input/Output
CHAPTER 3
INPUT/OUTPUT
In this chapter, you will:
Learn what a stream is and examine input and output
streams
Explore how to read data from the standard input device
Learn how to use predefined functions in a program
Explore how to use the input stream functions get,
ignore, fill, putback, and peek
Become familiar with input failure
Learn how to write data to the standard output device
Discover how to use manipulators in a program to format
output
Learn how to perform input and output operations with the
string data type
Become familiar with file input and output
Input/Output Streams
• I/O is a sequence of bytes, called a stream of bytes,
from the source to the destination.
• The bytes are usually characters, unless the program
requires other types of information such as a graphic
image or digital speech.
• A stream is a sequence of characters from the source to
the destination.
Input Stream: A sequence of characters from an input
device to the computer.
Output Stream: A sequence of characters from the
computer to an output device.
I/O STREAMS AND STANDARD I/O DEVICES
To extract (that is, receive) data from keyboard and send output to the
screen, every C++ program must use the header file iostream.
This header file, iostream, contains definitions of two data types,
istream (input stream) and ostream (output stream).
The header file, iostream, contains the declaration of two
variables, cin (stands for common input), pronounced see-in, and
cout (stands for common output), pronounced see-out, and the
declaration is similar to the following C++ statements:
istream cin;
ostream cout;
To use cin and cout every C++ program must use the
preprocessor directive
#include <iostream>
Variables of the type istream are called input stream
variables.
Variables of the type ostream are called output stream
variables.
A stream variable is either an input stream variable or an
output stream variable.
cin and the Extraction Operator (>>)
Consider the following C++ statement:
cin>>payRate;
If you type 15.50, the value stored in payRate after the execution
of this statement is 15.50.
The extraction operator >> is binary. The left-hand operand is an
input stream variable such as cin. The right-hand operand is a
variable of a simple data type.
The purpose of an input statement is to read and store values in a
memory location and only variables refer to memory locations, the
items (that is, right hand operand in the case of the extraction
operator, >>) must be a variable in an input statement.
• The syntax of an input statement using cin and the
extraction operator >> is
cin>>variable>>variable...;
Every occurrence of >> extracts the next data item from the
input stream.
You can read both payRate and hoursWorked via a single
cin statement by using the following code:
cin>>payRate>>hoursWorked;
There is no difference between the preceding cin statement
and the following two cin statements.
cin>>payRate;
cin>>hoursWorked;
When scanning for the next input, >> skips all whitespaces.
Whitespace characters consist of blanks and certain
nonprintable characters, such as tabs and the newline
character.
Whether the input is
15.50 48.30
or
15.50 48.30
or
15.50
48.30
The input statement:
cin>>payRate>>hoursWorked;
would store 15.50 in payRate and 48.30 in hoursWorked.
Suppose the input is 2. How does >> distinguish between character 2
and the number 2?
This is distinguished by the right hand operand of >>.
If the right hand operand, that is, variable, is of type char, input 2 is
treated as character 2 (recall that in this case, the ASCII value of 2
will be stored). And if the right-hand operand is of the type int (or
double), input 2 is treated as the number 2.
Now consider the input 25 and the statement:
cin>>a;
where a is a variable of some simple data type.
If a is of the data type char, then only the single character 2 will be
stored in a.
If a is of the data type, say int, then 25 will be stored in a.
If a is of the type double, then the input 25 is converted to a
decimal number with zero decimal part.
Consider the statement
cin>>a;
where a is a variable of some simple data type.
When reading data into a char variable, after skipping
any leading whitespace characters, the extraction operator
>> finds and stores only the next character; reading stops
after a single character.
To read data into an int or double variable, after
skipping all leading whitespace characters and reading the
plus or minus sign (if any), the extraction operator >>
reads the digits of the number, including the decimal point
for floating-point variables, and stops when it finds a
whitespace character or a character other than a digit.
Example 3-1
int a,b;
double z;
char ch,ch1,ch2;
1
2
Statement
cin>>ch;
cin>>ch;
Input
A
AB
3
4
cin>>a;
cin>>a;
48
46.35
5
6
7
8
9
cin>>z;
cin>>z;
cin>>z>>a;
cin>>a>>b;
cin>>a>>ch>>z;
74.35
39
65.78 38
4 60
57 A 26.9
Value Stored in Memory
ch='A'
ch='A', 'B' is held
for later input
a=48
a=46, .35 is held
for later input
z=74.35
z=39.0
z=65.78, a=38
a=4, b=60
a=57, ch='A', z=26.9
10
11
cin>>a>>ch>>z;
57
cin>>a>>ch>>z;
26.9
57
A
a=57, ch='A', z=26.9
A
12
cin>>a>>ch>>z;
26.9
57A26.9
13
cin>>z>>ch>>a;
36.78B34
14
cin>>z>>ch>>a;
36.78
B34
15
cin>>a>>b>>z;
11 34
a=57, ch='A', z=26.9
a=57, ch='A', z=26.9
z=36.78, ch='B',
a=34
z=36.78, ch='B',
a=34
a=11, b=34, Computer
waits for the next
number
16
cin>>a>>z;
46 32.4 68 a=46, z=32.4, 68 is
held for later input
17
cin>>ch>>a;
256
ch='2', a=56
18
cin>>a>>ch;
256
19
cin>>ch1>>ch2;
A B
a=256, computer
waits for the input
value for ch.
ch1 = 'A', ch2 = 'B’
• During program execution, when entering character data such
as letters, you do not enter the single quotes around the
character.
• Entering a char value into an int or double variable causes
serious errors, called input failure.
USING PREDEFINED FUNCTIONS IN A PROGRAM
• A function, also called subprogram, is a set of instructions.
• When a function is activated, that is, executed, it accomplishes
something.
• The function main is executed automatically when we execute a
program.
• Other functions are executed only when they are called.
• The programming language C++ comes with a wealth of functions.
• Predefined functions are organized as a collection of libraries,
called header files.
• A particular header file may contain several functions.
• To use a particular function, you need to know the name of the
function and a few other things.
• A very useful function, pow, called the power function, can be
used to calculate xy in a program. That is, pow(x,y) = xy.
• pow(2,3)= 23 = 8 and pow(4,0.5) = 40.5 = 2.
• The numbers x and y that you use in the function pow are
called the arguments or parameters of the function pow.
• In pow(2,3), the parameters are 2 and 3.
• An expression such as pow(2,3) is called a function call.
• The header file cmath contains the specification of the
function pow.
To use a predefined function in a program, you need to know
the name of the header file containing the specification of the
function and include that header file in the program.
In addition, you need to know the name of the function, the
number of parameters the function takes, and the type of each
parameter. You must also be aware of what the function is
going to do.
To use the function pow, you must include the header file
cmath.
The function pow has two parameters, both of which are
numbers. The function calculates the first parameter to the
power of the second parameter.
cin and the get Function
Consider the declaration:
char ch1, ch2;
int num;
and the input
A 25
Now consider the statement:
cin>>ch1>>ch2>>num;
• When the computer executes this statement, A is stored in ch1, blank
is skipped by >>, 2 is stored in ch2, and 5 is stored in num.
• If we intended to store A in ch1, blank in ch2 and 25 in num? It is
clear that we can not use the extraction operator >>.
The get function inputs the very next character (including
whitespaces) from the input stream and stores in the memory location
indicated by its argument.
The syntax of cin together with the get function to read a character
is:
cin.get(varChar);
where varChar is a char variable.
varChar is called the argument or parameter of the function.
The next input character is stored in varChar.
Now, again, consider the input
A 25
We can effectively use the get function as follows:
cin.get(ch1);
cin.get(ch2);
cin>>num;
to store A in ch1, blank in ch2, and 25 in num.
The above set of statements is equivalent to the following:
cin>>ch1;
cin.get(ch2);
cin>>num;
cin and the ignore Function
To process partial data, say with in a line, we can effectively use the
ignore function to discard some portion of the input.
The syntax to use the function ignore is:
cin.ignore(intExp,chExp);
where intExp is an integer expression yielding an integer value
and chExp is a char expression.
Suppose intExp yields a value, say m. This statement says, ignore
the next m characters or until the character specified by chExp,
whichever comes first.
Consider the following statement:
cin.ignore(100,'\n');
The execution of this statement will ignore the next 100 characters or
until the newline character is found whichever comes first.
The execution of the statement:
cin.ignore(100,'A');
will result in ignoring the first 100 characters or until the character
'A' is found, whichever comes first.
Example 3-2
int a,b;
Suppose the input is:
25 67 89 43 72
12 78 34
Consider the statements:
cin>>a;
cin.ignore(100,'\n');
cin>>b;
• The first statement cin>>a; stores 25 in a.
• The second statement, cin.ignore(100,'\n'); discards all of
the remaining numbers in the first line.
• The third statement cin>>b; stores 12 (from the next line) in b.
Example 3-3
char ch1,ch2;
Suppose the input is
Hello there. My name is Mickey.
Now consider the statements:
cin>>ch1;
cin.ignore(100,'.');
cin>>ch2;
• The first statement cin>>ch1; stores 'H' in ch1.
• The second statement, cin.ignore(100,'.' ); results in
ignoring all characters until '.' (period).
• The third statement cin>>ch2; stores 'M' (from the same line) in
ch2.
The peek and the putback Functions
The putback function places the previous character extracted by
the get function from an input stream back to that stream.
The peek function returns the next character from the input stream
but it does not remove the character from that stream, that is, the next
input character would be the same.
The syntax to use the function putback is:
istreamVar.putback(ch);
where istreamVar is an input stream variable, such as cin, and
ch is a char variable.
The syntax to use the function peek is:
ch = istreamVar.peek();
where istreamVar is an input stream variable, such as cin, and
ch is a char variable.
Example 3-4
//Functions peek and putback
#include <iostream>
using namespace std;
int main()
{
char ch;
cout<<"Line 1: Enter a string: ";
//Line 1
cin.get(ch);
//Line 2
cout<<endl;
//Line 3
cout<<"Line 4: After first cin.get(ch); "
<<"ch = "<<ch<<endl;
//Line 4
cin.get(ch);
//Line 5
cout<<"Line 6: After second cin.get(ch); "
<<"ch = "<<ch<<endl;
//Line 6
cin.putback(ch);
//Line 7
cin.get(ch);
//Line 8
cout<<"Line 9: After putback and then "
<<"cin.get(ch); ch = "<<ch<<endl;
ch = cin.peek();
//Line 9
//Line 10
cout<<"Line 11: After cin.peek(); ch = "
<<ch<<endl;
//Line 11
cin.get(ch);
//Line 12
cout<<"Line 13: After cin.get(ch); ch = "
<<ch<<endl;
//Line 13
return 0;
}
Sample Run: In this sample run, the user input is in red.
Line 1: Enter a string: abcd
Line 4: After first cin.get(ch); ch = a
Line 6: After second cin.get(ch); ch = b
Line 9: After putback and then cin.get(ch); ch = b
Line 11: After cin.peek(); ch = c
Line 13: After cin.get(ch); ch = c
The Dot Notation Between I/O Stream Variables and
I/O Functions: A Precaution
To use the get function we used statements such as
cin.get(ch);
Missing dot will result in compile time error. For example, in the statement
cin.get(ch);
cin and get are two separate identifiers, while in the statement
cinget(ch);
cinget becomes a new identifier and the compiler might be trying to
resolve the problem of an undeclared identifier in the program. Similarly,
missing parentheses will result in compile time error.
• Several functions are associated with an istream variable, each
doing a specific job.
• The functions get, ignore, and so on are members of the data type
istream.
• Called the dot notation, the dot separates the input stream variable
name from the member, or function, name.
• In C++, the dot is an operator called the member access operator.
• C++ has a special name for the data types istream and ostream.
• The data types istream and ostream are called classes.
• The variables cin and cout also have special names, called
objects. cin is called an istream object
• cout is called an ostream object.
• Stream variables are called stream objects.
INPUT FAILURE
• Many things can go wrong during program execution.
• A program that is syntactically correct might produce incorrect
results.
Suppose that a part-time employee’s paycheck is calculated by using
the following formula:
wages = payRate * hoursWorked;
If you accidentally type + in place of *, the calculated wages would
be incorrect, even though the statement containing a + is
syntactically correct.
• What about an attempt to read invalid data?
• What would happen if you tried to input a letter into an int variable?
• If the input data did not match the corresponding variables, the
program would run into problems.
• Trying to read a letter into an int or double variable would result
in an input failure.
Consider the following statements
int a, b, c;
double x;
If the input is
W 54
then the statement
cin>>a>>b;
would result in an input failure because you are trying to input the
character 'W' into the int variable a.
If the input is
35 67.93 48 78
then the input statement
cin>>a>>x>>b;
would result in storing 35 in a, 67.93 in x, and 48 in b.
Now consider the following read statement with the previous input (the
input with three values):
cin>>a>>b>>c;
This statement stores 35 in a and 67 in b. The reading stops at . (the
decimal point). Because the next variable c is of the data type int, the
computer tries to read . into c, which is an error. The input stream then
enters a state called the fail state.
• What actually happens when the input stream enters the fail state?
• Once an input stream enters a fail state, all further I/O statements
using that stream are ignored.
• Unfortunately, the program quietly continues to execute with whatever
values are stored in variables and produce incorrect results.
Example 3-5
//Input Failure program
#include <iostream>
using namespace std;
int main()
{
int a = 10;
//Line 1
int b = 20;
//Line 2
int c = 30;
//Line 3
int d = 40;
//Line 4
cout<<"Line 5: Enter four integers: ";
//Line 5
cin>>a>>b>>c>>d;
//Line 6
cout<<endl;
//Line 7
cout<<"Line 8: The numbers you entered are:"
<<endl;
//Line 8
cout<<"Line 9: a = "<<a<<", b = "<<b
<<", c = "<<c<<", d = "<<d<<endl;
return 0;
}
Sample Run 1: The user input is in red.
Line 5: Enter four integers: 34 K 67 28
Line 8: The numbers you entered are:
Line 9: a = 34, b = 20, c = 30, d = 40
//Line 9
The clear Function
When an input stream enters the fail state, the system ignores all further
I/O using that stream. You can use the stream function clear to restore
the input stream to a working state.
The syntax to use the function clear is:
istreamVar.clear();
Here istreamVar is an input stream variable, such as cin.
OUTPUT AND FORMATTING OUTPUT
Syntax of cout when used together with the insertion operator << is
cout<<expression or manipulator
<<expression or manipulator...;
• expression is evaluated, its value is printed, and
manipulator is used to format the output.
• The simplest manipulator that you have used so far is endl, which
is used to move the cursor to the beginning of the next line.
setprecision
The general form of setprecision is:
setprecision(n)
where n is the number of decimal places.
The statement
cout<<setprecision(2);
will output all decimal numbers up to two decimal places until it is
reset.
To use the manipulator setprecision, the program must include
the header file iomanip.
#include <iomanip>
fixed
• To output floating-point numbers in a fixed decimal format, you use
the manipulator fixed.
• The following statement sets the output of floating-point numbers in
a fixed decimal format on the standard output device:
cout<<fixed;
• After the preceding statement executes, all floating-point numbers
are displayed in the fixed-decimal format until the manipulator
fixed is disabled.
• You can disable the manipulator fixed by using the stream member
function unsetf.
• The following statement disables the manipulator fixed on the
standard output device, you use:
cout.unsetf(ios::fixed);
• After the manipulator fixed is disabled, the output of the floatingpoint numbers return to their default settings.
• The manipulator scientific is used to output floating-point
numbers in scientific format.
showpoint
• If the decimal part of a decimal number is zero, then when you
instruct the computer to output the decimal number in a fixed decimal
format, the output may not show the decimal point and the decimal
part.
• To force the output to show the decimal point and trailing zeros, you
use the manipulator showpoint.
• The following statement sets the output of decimal numbers with a
decimal point and trailing zeros on the standard input device:
cout<<showpoint;
• The following statement sets the output of a floating-point number in
a fixed decimal format with the decimal point and trailing zeros on the
standard output device:
cout<<fixed<<showpoint;
Example 3-7
//Example: setprecision, fixed, showpoint
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x,y,z;
x = 15.674;
//Line 1
y = 235.73;
//Line 2
z = 9525.9864;
//Line 3
cout<<fixed<<showpoint;
//Line 4
cout<<setprecision(2)
<<"Line 5: setprecision(2)"<<endl;
//Line 5
cout<<"Line 6: x = "<<x<<endl;
//Line 6
cout<<"Line 7: y = "<<y<<endl;
//Line 7
cout<<"Line 8: z = "<<z<<endl;
//Line 8
cout<<setprecision(3)
<<"Line 9: setprecision(3)"<<endl;
//Line 9
cout<<"Line 10: x = "<<x<<endl;
//Line 10
cout<<"Line 11: y = "<<y<<endl;
//Line 11
cout<<"Line 12: z = "<<z<<endl;
//Line 12
cout<<setprecision(4)
<<"Line 13: setprecision(4)"<<endl;
//Line 13
cout<<"Line 14: x = "<<x<<endl;
//Line 14
cout<<"Line 15: y = "<<y<<endl;
//Line 15
cout<<"Line 16: z = "<<z<<endl;
//Line 16
cout<<"Line 17: "
<<setprecision(3)<<x<<"
"
<<setprecision(2)<<y<<"
"
<<setprecision(4)<<z<<endl;
return 0;
}
//Line 17
Output:
Line 5: setprecision(2)
Line 6: x = 15.67
Line 7: y = 235.73
Line 8: z = 9525.99
Line 9: setprecision(3)
Line 10: x = 15.674
Line 11: y = 235.730
Line 12: z = 9525.986
Line 13: setprecision(4)
Line 14: x = 15.6740
Line 15: y = 235.7300
Line 16: z = 9525.9864
Line 17: 15.674
235.73
9525.9864
• The stream function setf can be used to set fixed, scientific,
and showpoint.
• In this case, fixed, scientific, and showpoint are referred to
as ios::fixed, ios::scientific, and ios::showpoint,
respectively, and are called formatting flags.
• Both the flags ios::fixed and ios::scientific are part of
ios::floatfield, which is a data type in C++.
• When setting the fixed or scientific flag, to ensure that only either the
ios::fixed or ios::scientific flag is set, you must pass
ios::floatfield as a second argument to the function setf.
cout.setf(ios::fixed,ios::floatfield);
• The following statement sets the flag ios::showpoint to output
floating-point numbers with a decimal point and trailing zeros on the
standard output device:
cout.setf(ios::showpoint);
• C++ provides the manipulator setiosflags, to set the flags
ios::fixed, ios::scientific, and ios::showpoint.
• To use the manipulator setiosflags , the program must include
the header file iomanip.
• The following statement uses the manipulator setiosflags to set
the flags ios::fixed and ios::showpoint on the standard
output device:
cout<<setiosflags(ios::fixed);
cout<<setiosflags(ios::showpoint);
• You can specify more than one flag in the manipulator
setiosflags by separating the flags with the symbol |.
• The following statement sets both the flags ios::fixed and
ios::showpoint on the standard output device:
cout<<setiosflags(ios::fixed | ios::showpoint);
setw
setw(n) - output the value of the next expression in n columns.
The output is right justified.
If the number of specified columns is less than the number of
columns required by the output, then the output is automatically
expanded to the required number of columns.
Unlike setprecision, which controls the output of all floatingpoint numbers until it is reset, setw controls the output of only the
next expression.
To use the manipulator setw, the program must include the header
file iomanip.
Example 3-8
//Example: setw
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x = 19;
int a = 345;
double y = 76.384;
cout<<fixed<<showpoint;
//Line 1
//Line 2
//Line 3
//Line 4
}
cout<<"12345678901234567890"<<endl;
//Line 5
cout<<setw(5)<<x<<endl;
cout<<setw(5)<<a<<setw(5)<<"Hi"
<<setw(5)<<x<<endl<<endl;
//Line 6
cout<<setprecision(2);
cout<<setw(6)<<a<<setw(6)<<y
<<setw(6)<<x<<endl;
cout<<setw(6)<<x<<setw(6)<<a
<<setw(6)<<y<<endl<<endl;
//Line 8
cout<<setw(5)<<a<<x<<endl;
cout<<setw(2)<<a<<setw(4)<<x<<endl;
return 0;
//Line 11
//Line 12
//Line 7
//Line 9
//Line 10
Output:
12345678901234567890
19
345
Hi
19
345 76.38
19
19
345 76.38
34519
345 19
ADDITIONAL OUTPUT FORMATTING TOOLS
fill and setfill
• In the manipulator setw if the number of columns specified are
more than the number of columns required by the expression, the
output of the expression is right justified and the unused columns to
the left are filled with spaces.
• The output stream variables, such as cout, can use the function
fill and/or the manipulator setfill to fill the unused columns
with a character other than the space.
The syntax to use the function fill is:
ostreamVar.fill(ch);
where ostreamVar is an output stream variable and ch is a
character. For example, the statement
cout.fill('*');
sets the filling character to '*' on the standard output screen.
The syntax to use the manipulator setfill is:
ostreamVar<<setfill(ch);
where ostreamVar is an output stream variable and ch is a
character.
The statement
cout<<setfill('#');
sets the filling character to '#'.
Example 3.9
//Example: fill and setfill
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x = 15;
//Line 1
int y = 7634;
//Line 2
cout<<"12345678901234567890"<<endl;
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
//Line 3
cout.fill('*');
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
//Line 5
//Line 4
//Line 6
cout<<setw(5)<<x<<setw(7)<<setfill('#')
<<y<<setw(8)<<"Warm"<<endl;
//Line 7
cout<<setw(5)<<setfill('@')<<x
<<setw(7)<<setfill('#')<<y
<<setw(8)<<setfill('^')<<"Warm"
<<endl;
//Line 8
cout.fill(' ');
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
return 0;
}
Output:
12345678901234567890
15
7634
Warm
***15***7634****Warm
***15###7634####Warm
@@@15###7634^^^^Warm
15
7634
Warm
//Line 9
//Line 10
The left and right Manipulators
• To left-justify the output, you use the manipulator left.
• The syntax to set the manipulator left is
ostreamVar<<left;
where ostreamVar is an output stream variable.
• The following statement sets the output to be left-justified on the
standard output device:
cout<<left;
• You can disable the manipulator left by using the stream function
unsetf. The syntax to disable the manipulator left is
ostreamVar.unsetf(ios::left);
where ostreamVar is an output stream variable. Disabling the
manipulator left returns the output to the settings of the default
output format.
• The following statement disables the manipulator left on the
standard output device:
cout.unsetf(ios::left);
• The syntax to set the manipulator right is
ostreamVar<<right;
where ostreamVar is an output stream variable.
• The following statement sets the output to be right-justified on the
standard output device:
cout<<right;
Example 3-10
//Example: left justification
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x = 15;
int y = 7634;
//Line 1
//Line 2
cout<<left;
//Line 3
cout<<"12345678901234567890"<<endl;
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
//Line 4
cout.fill('*');
//Line 6
//Line 5
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
//Line 7
cout<<setw(5)<<x<<setw(7)<<setfill('#')<<y
<<setw(8)<<"Warm"<<endl;
//Line 8
cout<<setw(5)<<setfill('@')<<x
<<setw(7)<<setfill('#')<<y
<<setw(8)<<setfill('^')<<"Warm"<<endl; //Line 9
}
cout.unsetf(ios::left);
cout.fill(' ');
//Line 10
//Line 11
cout<<setw(5)<<x<<setw(7)<<y
<<setw(8)<<"Warm"<<endl;
return 0;
//Line 12
Output:
12345678901234567890
15
7634
Warm
15***7634***Warm****
15***7634###Warm####
15@@@7634###Warm^^^^
15
7634
Warm
The flush Function
• Both the manipulator endl and the newline escape sequence \n
position the cursor at the beginning of the next line on the output
device.
• When a program sends output to an output device, the output first
goes to the buffer in the computer.
• Whenever the buffer becomes full, the output is sent to the output
device.
• As soon as the manipulator endl is encountered, the output from the
buffer is sent to the output device immediately, even if the buffer is
not full.
• The manipulator endl positions the cursor at the beginning of the
next line on an output device and helps clear the buffer.
• It is quite possible that sometimes you may not see the entire output
because when the program terminates, the buffer at that time may not
be full.
• In C++, you can use the function flush to clear the buffer, even if
the buffer is not full.
• In contrast to the manipulator endl, the function flush does not
move the cursor to the beginning of the next line.
• The syntax to use the flush function is:
ostreamVar.flush();
where ostreamVar is an output stream variable, such as cout.
• Just like endl, the function flush can be used as a manipulator. In
such a case, flush is used in an output statement without the
parentheses. For example, the following statement sends the output
from the buffer to the standard output device:
cout<<flush;
Example 3-11
Consider the following statements in which num is an int variable:
cout<<"Enter an integer: " ;
cin>>num;
cout<<endl;
//Line 1
//Line 2
//Line 3
• The statement at Line 1 outputs the following text:
Enter an integer:
• After outputting this line, the cursor stays positioned after the colon.
• The output of the statement at Line 1 first goes to the buffer.
• If the buffer is not full, this line of text might not be displayed.
• You could put the manipulator endl at the end of the statement at
Line 1. However, by doing so, after printing the line of text, the
cursor is positioned at the beginning of the next line.
• The user is prompted to enter the number in the following line
• Suppose that the statement at Line 1 is replaced by the following
statement:
cout<<"Enter an integer: "<<flush;
//Line 1
• In this case, the line of text,
Enter an integer:
is displayed on the standard output device even if the buffer is not full.
Moreover, after outputting the line of text, the cursor stays positioned
after the colon; the user will then enter the number after the colon.
• To use stream functions such as get, ignore, fill, clear, and
setf in a program, the program must include the header file
iostream.
• There are two types of manipulators: those with parameters and those
without parameters.
• Manipulators with parameters are called parameterized stream
manipulators.
• Manipulators such as setprecision, setw, setfill, and
setiosflags are parameterized.
• Manipulators such as endl, fixed, scientific, showpoint,
and left are without parameters.
• Because flush can also be used as a manipulator without any
arguments, flush is a manipulator without parameters, too.
• To use a parameterized stream manipulator—that is, a stream
manipulator with parameters—in a program, you must include the
header file iomanip.
• Manipulators without parameters are part of the iostream header
file and, therefore, do not require inclusion of the header file
iomanip.
Input/Output and the string Type
• You can use an input stream variable, such as cin, and the extraction
operator >> to read a string into a variable of the data type string.
• If the input is the string "Shelly", the following code stores this
input into the string variable name:
string name; // declaration
cin>>name;
// input statement
• The extraction operator skips any leading whitespace characters and
that reading stops at a whitespace character.
• You cannot use the extraction operator to read strings that contain
blanks.
• If the input is
Alice Wonderland
the value of the variable name after the following statement executes
is "Alice":
cin>>name;
• To read a string containing blanks, you can use the function
getline .
• The syntax to use the function getline is
getline(istreamVar, strVar);
where istreamVar is an input stream variable and strVar is a
variable of the type string. The reading is delimited by the newline
character, '\n'.
• The function getline reads until it reaches the end of the current
line.
• The newline character is also read but not stored in the string
variable.
• Consider the following statement:
string myString;
• If the input is 29 characters,
bbbbHello there. How are you?
where b represents a blank, after the statement
getline(cin,myString);
the value of myString is
myString =
"
Hello there. How are you?"
File Input/Output
File: An area in secondary storage used to hold information.
For file I/O, the following steps are necessary.
1. Include the header file fstream in the program. So the following
statement is needed.
#include <fstream>
2. Declare file (fstream) variables. For example the statements:
ifstream inData;
ofstream outData;
declare the variable inData for input and outData for output. That is,
inData is an input (file) stream variable and outData is an output
(file) stream variable.
3. Open Files
The general syntax for opening a file is
fileStreamVariable.open(sourceName,
fileOpeningMode);
Here fileStreamVariable is a file stream variable,
sourceName is the name of the input/output file, and
fileOpeningMode specifies the mode in which the file is to be
opened.
• Suppose declaration of Step 2.
• Suppose that the input data is stored in a file called prog.dat on a
floppy disk in drive A:.
• Save the output in a file called prog.out on a floppy disk in drive
A:.
• The following statements associate inData with prog.dat and
outData with prog.out.
inData.open("A:prog.dat"); //open input file
outData.open("A:prog.out"); //open output file
Step 4:
Use the (file) stream variable together with >> or << or with other
functions for input/Output.
The syntax for using >> or << with file variables is exactly similar to
the syntax of cin and cout.
The statement
inData>>payRate;
reads the data from the file prog.dat and stores it in the variable
payRate
The statement
outData<<"The pay check is: "<<pay<<endl;
stores the output line, which is: The pay check is: 565.78,
in the file prog.out. Here we are assuming that the pay was
calculated as 565.78.
Close File
inData.close();
outData.close();
#include <fstream>
//Add additional header files you use
using namespace std;
int main()
{
//Declare file stream variables such as the following
ifstream inData;
ofstream outData;
...
//Open files
inData.open("A:prog.dat"); //open input file
outData.open("A:prog.out"); // open output file
//Code for data manipulation
//Close files
inData.close();
outData.close();
return 0;
}
PROGRAMMING EXAMPLE: MOVIE TICKET SALE
AND DONATION TO CHARITY
A movie in a local theater is in great demand. To help a local charity, the
theater owner has decided to donate a portion of the gross amount
generated from the movie to the charity. This example designs and
implements a program that prompts the user to input the movie name,
adult ticket price, child ticket price, number of adult tickets sold,
number of child tickets sold, and percentage of the gross amount to be
donated to the charity. The output of the program is as follows.
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Movie Name: ....................... Duckey Goes to Mars
Number of Tickets Sold: ...........
2650
Gross Amount: ..................... $ 9150.00
Percentage of Gross Amount Donated:
Amount Donated: ................... $
10.00%
915.00
Net Sale: ......................... $ 8235.00
Input
The input to the program consists of the movie name, adult ticket price,
child ticket price, number of adult tickets sold, number of child tickets
sold, and percentage of the gross amount to be donated to the charity.
Output
The output is as shown above.
Problem Analysis and Algorithm Design
grossAmount = adultTicketPrice * noOfAdultTicketsSold
+ childTicketPrice * noOfChildTicketsSold;
The formulas to calculate the amount donated and the net sale amount
are given below.
1. Get the movie name.
2. Get the price of an adult ticket price.
3. Get the price of a child ticket price.
4. Get the number of adult tickets sold.
5. Get the number of child tickets sold.
6. Get the percentage of the gross amount donated to the charity.
7. Calculate the gross amount using the following formula:
grossAmount = adultTicketPrice * noOfAdultTicketsSold
+ childTicketPrice * noOfChildTicketsSold;
8. Calculate the amount donated to the charity using the following
formula:
amountDonated = grossAmount * percentDonation / 100;
9. Calculate the net sale amount using the following formula:
netSale = grossAmount – amountDonated;
Variables
string
movieName;
double
adultTicketPrice;
double
childTicketPrice;
int
noOfAdultTicketsSold;
int
noOfChildTicketsSold;
double
percentDonation;
double
grossAmount;
double
amountDonated;
double
netSaleAmount;
Formatting Output
• In the output, the first column is left-justified and the numbers in the
second column are right-justified.
• When printing a value in the first column, the manipulator left is
used; before printing a value in the second column, the manipulator
right is used.
• The empty space between the first and second columns is filled with
dots; the program uses the manipulator setfill to accomplish this
goal.
• In the lines showing the gross amount, amount donated, and net sale
amount, the space between the $ sign and the number is filled with
blank spaces.
• Before printing the dollar sign, the program uses the manipulator
setfill to set the filling character to blank.
• The following statements accomplish the desired output:
cout<<"-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"
<<"-*-*-*-*-*-*-*-*-*-*-*-*-*"<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Movie Name: "
<<right<<" "<<movieName<<endl;
cout<<left<<setw(35)<<"Number of Tickets Sold: "
<<setfill(' ')<<right<<setw(10)
<<noOfAdultTicketsSold + noOfChildTicketsSold
<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Gross Amount: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<grossAmount<<endl;
cout<<setfill('.')<<left<<setw(35)
<<"Percentage of Gross Amount Donated: "
<<setfill(' ')<<right
<<setw(9)<<percentDonation<<'%'<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Amount Donated: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<amountDonated<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Net Sale: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<netSaleAmount<<endl;
Main Algorithm
1. Declare the variables.
2. Set the output of the floating-point numbers to two decimal places in
a fixed decimal format with a decimal point and trailing zeros.
Therefore, you need to include the header file iomanip.
3. Prompt the user to enter a movie name.
4. Input (read) the movie name. Because the name of a movie might
contain more than one word (and, therefore, might contain blanks), the
program uses the function getline to input the movie name.
Moreover, because the function getline also reads the newline
character, after entering the movie name on a line, you need to press
the Enter key twice.
5. Prompt the user to enter the price of an adult ticket.
6. Input (read) the price of an adult ticket.
7. Prompt the user to enter the price of a child ticket.
8. Input (read) the price of a child ticket.
9. Prompt the user to enter the number of adult tickets sold.
10. Input (read) the number of adult tickets sold.
11. Prompt the user to enter the number of child tickets sold.
12. Input (read) the number of child tickets sold.
13. Prompt the user to enter the percentage of the gross amount donated.
14. Input (read) the percentage of the gross amount donated.
15. Calculate the gross amount.
16. Calculate the amount donated.
17. Calculate the net sale amount.
18. Output the results.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Step 1
string movieName;
double adultTicketPrice;
double childTicketPrice;
int noOfAdultTicketsSold;
int noOfChildTicketsSold;
double percentDonation;
double grossAmount;
double amountDonated;
double netSaleAmount;
cout<<fixed<<showpoint<<setprecision(2);
//Step 2
cout<<"Enter movie name: "<<flush;
//Step 3
getline(cin,movieName);
//Step 4
cout<<endl;
cout<<"Enter the price of an adult ticket: "<<flush;
//Step 5
cin>>adultTicketPrice;
//Step 6
cout<<endl;
cout<<"Enter the price of a child ticket: "<<flush;
//Step 7
cin>>childTicketPrice;
cout<<endl;
//Step 8
cout<<"Enter number of adult tickets sold: "<<flush;
//Step 9
cin>>noOfAdultTicketsSold;
//Step 10
cout<<endl;
cout<<"Enter number of child tickets sold: "<<flush;
//Step 11
cin>>noOfChildTicketsSold;
//Step 12
cout<<endl;
cout<<"Enter the percentage of donation: "<<flush;
//Step 13
cin>>percentDonation;
//Step 14
cout<<endl<<endl;
grossAmount = adultTicketPrice * noOfAdultTicketsSold +
childTicketPrice * noOfChildTicketsSold;
//Step 15
amountDonated = grossAmount * percentDonation / 100;
//Step 16
netSaleAmount = grossAmount - amountDonated;
//Step 17
//Step 18: Output results
cout<<"-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"
<<"-*-*-*-*-*-*-*-*-*-*-*-*-*"<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Movie Name: "
<<right<<" "<<movieName<<endl;
cout<<left<<setw(35)<<"Number of Tickets Sold: "
<<setfill(' ')<<right<<setw(10)
<<noOfAdultTicketsSold + noOfChildTicketsSold
<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Gross Amount: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<grossAmount<<endl;
cout<<setfill('.')<<left<<setw(35)
<<"Percentage of Gross Amount Donated: "
<<setfill(' ')<<right
<<setw(9)<<percentDonation<<'%'<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Amount Donated: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<amountDonated<<endl;
cout<<setfill('.')<<left<<setw(35)<<"Net Sale: "
<<setfill(' ')<<right<<" $"
<<setw(8)<<netSaleAmount<<endl;
return 0;
}
Sample Run: (In this sample run, the user input is in red):
Enter movie name: Duckey Goes to Mars
Enter the price of an adult ticket: 4.50
Enter the price of a child ticket: 3.00
Enter number of adult tickets sold: 800
Enter number of child tickets sold: 1850
Enter the percentage of donation: 10
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Movie Name: ....................... Duckey Goes to Mars
Number of Tickets Sold: ...........
2650
Gross Amount: ..................... $ 9150.00
Percentage of Gross Amount Donated: .. 10.00%
Amount Donated: ................... $ 915.00
Net Sale: ......................... $ 8235.00
PROGRAMMING EXAMPLE: STUDENT GRADE
Write a program that reads a student ID followed by five test scores.
The program should output the student ID, the five test scores, and the
average test score. Output the average test score with two decimal
places. Assume that the student ID is a character.
The data to be read is stored in a file called test.txt, and the file is
stored on a floppy disk in drive A:. The output should be stored in a file
called testavg.out, and the output file should be stored on the
floppy disk in drive A:.
Input: A file containing the student ID and five test scores.
Output: The student ID, five test scores and the average of the five test
scores. The output is to be saved in a file.
Problem Analysis and Algorithm Design
To find the average of five test scores, first we add the five test scores
and then divide the sum by 5. Now, the input data is in the form:
student ID followed by five test scores. Therefore, we first read the
student ID and then the five test scores. This discussion translates in
the following algorithm:
1. Read student ID and the five test score.
2. Output student ID and five test scores.
3. Calculate the average.
4. Output the average.
We will output the average test score in the fixed decimal format with
two decimal places.
Variables:
ifstream inFile;
//input file stream variable
ofstream outFile;
//output file stream variable
int test1, test2, test3, test4, test5; // variables
//to read five test scores
double average;
//variable to store average
//test score
char studentId;
//variable to store
//student ID
Main Algorithm
1.
2.
3.
4.
Declare the variables.
Open the input file.
Open the output file.
To output the floating-point numbers in a fixed decimal format with
a decimal point and trailing zeros, set the manipulators fixed and
showpoint. Also, to output the floating-point numbers with two
decimal places, set the precision to two decimal places.
5. Read the student ID.
6. Output the student ID.
7. Read the five test scores.
8. Output the five test scores.
9. Find the average test score.
10. Output the average test score.
11. Close the input and output files.
//Program to calculate average test score.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
//Declare variables; Step 1
ifstream inFile;
//input file stream variable
ofstream outFile; //output file stream variable
int test1, test2, test3, test4, test5;
double average;
char studentId;
inFile.open("a:test.txt");
//Step 2
outFile.open("a:testavg.out");
//Step 3
outFile<<fixed<<showpoint;
//Step 4
outFile<<setprecision(2);
//Step 4
cout<<"Processing data"<<endl;
inFile>>studentId;
//Step 5
outFile<<"Student ID: "<<studentId
<<endl;
//Step 6
inFile>>test1>>test2>>test3
>>test4>>test5;
//Step 7
outFile<<"Test scores: "<<setw(4)<<test1
<<setw(4)<<test2<<setw(4)<<test3
<<setw(4)<<test4
<<setw(4)<<test5<<endl;
//Step 8
average = static_cast<double>(test1+test2+test3+
test4+test5)/5.0;
//Step 9
outFile<<"Average test score: "<<setw(6)
<<average<<endl;
inFile.close();
//Step 11
outFile.close();
//Step 11
return 0;
}
//Step 10
Sample Run:
Input File: (contents of the file a:test.txt):
T 87 89 65 37 98
Output File: (contents of the file a:testavg.out)
Student ID: T
Test scores:
87
Average test score:
89
65
75.20
37
98