Chap02 - Input Output
Chap02 - Input Output
Chapter 2
Input Output
iostream header file
cout <<
Input ( cin , get , getline )
cin and Extraction Operator >>
🠶 Input received from keyboard
🠶 Note: cin skips the whitespace characters like
spaces(‘ ’), newlines(‘\n’), tabs(‘\t’), etc.
🠶 Syntax: cin>> variable1 >> variable2 ...;
e.g. cin>>payRate;
cin>>hoursWorked;
OR
// more than 1 input
cin>>payRate>>hoursWorked;
Input Data Type
cin and get Function
Scenario 1:
char ch1, ch2;
int num;
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
🠶 Read next character (including blank space)
🠶 The syntax of cin and get function combined:
cin.get(variable);
🠶 Example:
Input : A 25
Statements: cin.get(ch1);
cin.get(ch2);
cin>>num;
=> Read ‘A’ into ch1, blank space into ch2 ,
25 into num
cin and get Function
Scenario 2:
char gender;
int age;
cout<<“Enter num1 = “;
cin>>num1;
cout<<“Enter num2 = “;
cin>>num2;
return 0;
}
Output ( cout )
cout and insertion operator <<
🠶 Output sent to screen for display
🠶 Syntax: cout<<expression/manipulator
<<expression/
manipulator...;
🠶 Example
⮚ cout << “I am 18!”;
⮚ cout << “I am " << “18!";
⮚ cout << “I am ";
cout << “18!";
⮚ int age = 18;
The endl Manipulator
🠶 You can use the endl manipulator to start a
new line of output. This will produce two
lines of output:
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!
Formatting Output by 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
:
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
🠶 Output is right justified by default
🠶 cout<<left;
✔to left justify the output
✔disable left by using - cout.unsetf(ios::left);
🠶 cout<<right;
✔to right justify the output
The left & right Manipulator -
: Example
int main( ) {
double x = 123.456, y = 78.9, z = 0.321;
13 spaces