Chap03 - Input Output
Chap03 - Input Output
Chapter 3
Input Output
iostream header file
e.g. cin>>payRate;
cin>>hoursWorked;
OR
cin>>payRate>>hoursWorked; // more than 1
input
Input Data Type
cin and get Function
Input : A 25
Statement : cin>>ch1>>ch2>>num;
Reads ‘A’ into ch1, ‘2’ into ch2, 5 into num
Blank space was not read
cin and get Function
• The get function
− Inputs next character (including blank
space)
• The syntax of cin and the get function:
cin.get(varChar);
• Example:
Input : A 25
Statements: cin.get(ch1);
cin.get(ch2);
cin>>num;
=> Read ‘A’ into ch1, blank space into ch2 ,
25 into num
Input Failure
Programming is
fun!
The \n Escape Sequence
• You can also use the \n escape sequence
to start a new line of output. This will
produce two lines of output:
Programming is
fun!
3.3 Formatting Output by Manipulator
• Two types of manipulators:
− With parameters
− Without parameters
int main( ) {
int x = 22, y = 8899;
return 0;
}
The setprecision(n) Manipulator
int main( ) {
double num = 5.6789;
cout << num << endl;
cout << setprecision(4) << num << endl;
cout << setprecision(3) << num << endl;
cout << setprecision(2) << num << endl;
cout << setprecision(1) << num << endl;
return 0;
The fixed Manipulator - Example
#include <iostream>
#include <iomanip>
using namespace std;
int main( ) {
double num = 5.6789;
cout << num << endl << endl;
cout.unsetf(ios::fixed);
cout << "Without fixed manipulatior" << endl;
cout << setprecision(3) << num << endl;
cout << setprecision(2) << num << endl << endl;
return 0;
}
The showpoint Manipulator
• Causes a decimal point and trailing zeroes to
be displayed, even if there is no fractional part
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main( ) {
return 0;
}
The showpoint Manipulator - Example
#include <iostream>
#include <iomanip>
using namespace std;
int main( ) {
return 0;
}
The left & right Manipulator
• cout<<right;
to right justify the output
The left & right Manipulator -
Example
#include <iostream>
#include <iomanip>
using namespace std;
int main( ) {
double x = 123.456, y = 78.9, z = 0.321;
return 0;
}
Other I/O Manipulators
13 spaces