0% found this document useful (0 votes)
2K views11 pages

Input Output in C++ PDF

C++ provides input and output streams for performing input and output operations. Input streams are used to read data into a program from devices like keyboards, while output streams write data from memory to devices like displays. Common header files for input/output in C++ include iostream for streams like cin and cout, iomanip for stream manipulators, and fstream for file streams. Common stream objects are cout for standard output, cin for standard input, cerr for standard errors, and clog for buffered standard errors. Loops in C++ like for and while loops repeatedly execute a block of code until a condition is met.

Uploaded by

All Tvwnz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views11 pages

Input Output in C++ PDF

C++ provides input and output streams for performing input and output operations. Input streams are used to read data into a program from devices like keyboards, while output streams write data from memory to devices like displays. Common header files for input/output in C++ include iostream for streams like cin and cout, iomanip for stream manipulators, and fstream for file streams. Common stream objects are cout for standard output, cin for standard input, cerr for standard errors, and clog for buffered standard errors. Loops in C++ like for and while loops repeatedly execute a block of code until a condition is met.

Uploaded by

All Tvwnz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

INPUT / OUTPUT IN C++

C++ comes with libraries that provide us with many ways for performing input and output. In C++ input
and output are performed in the form of a sequence of bytes or more commonly known as streams.

• Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the
main memory then this process is called input.

• Output Stream: If the direction of flow of bytes is opposite, i.e., from main memory to device
(display screen) then this process is called output.

Header files available in C++ for Input/Output operations are:

1. iostream: iostream stands for standard input-output stream. This header file contains
definitions to objects like cin, cout, cerr etc.

2. iomanip: iomanip stands for input output manipulators. The methods declared in this file are
used for manipulating streams. This file contains definitions of setw, setprecision, etc.

3. fstream: This header file mainly describes the file stream. This header file is used to handle the
data being read from a file as input or data being written into the file as output.

The two keywords cout in C++ and cin in C++ are used very often for printing outputs and taking inputs
respectively. These two are the most basic methods of taking input and printing output in C++. To use
cin and cout in C++ one must include the header file iostream in the program.

1. Standard output stream (cout):

The standard output device is the display screen. The C++ cout statement is the instance of the ostream
class. It is used to produce output on the standard output device which is usually the display screen. The
data needed to be displayed on the screen is inserted in the standard output stream (cout) using the
insertion operator(<<)

In the above program the insertion operator(<<) inserts the value of the string variable sample followed
by the string “A computer science portal for geeks” in the standard output stream cout which is then
displayed on screen.

#include <iostream>
using namespace std;
int main()
{
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}

#include <iostream>

using namespace std;

int main() {

char str[] = "Hello C++";

cout << "Value of str is : " << str << endl;

return 0;

2. Standard input stream (cin):

Usually, the input device in a computer is the keyboard. C++ cin statement is the instance of the
class istream and is used to read input from the standard input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator
extracts the data from the object cin which is entered using the keyboard.

#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
return 0;
}
#include <iostream>

using namespace std;

int main() {

char name[50];

cout << "Please enter your name: ";

cin >> name;

cout << "Your name is: " << name << endl;

return 0;
}

The above program asks the user to input the age. The object cin is connected to the input device. The
age entered by the user is extracted from cin using the extraction operator (>>) and the extracted data is
then stored in the variable age present on the right side of the extraction operator.

3. The Standard Error Stream (cerr)

The C++ cerr is the standard error stream which is used to output the errors. This is also an instance of
the ostream class. As cerr in C++ is un-buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the error message and display later.

The main difference between cerr and cout comes when you would like to redirect output using “cout”
that gets redirected to file if you use “cerr” the error doesn’t get stored in file. (This is what un-buffered
means ..It cant store the message)

#include <iostream>
using namespace std;
int main()
{
cerr << "An error occured";
return 0;
}

#include <iostream>

using namespace std;

int main() {

char str[] = "Unable to read....";

cerr << "Error message : " << str << endl;

return 0;

4. The Standard Log Stream (clog):

This is also an instance of ostream class and used to display errors but unlike cerr the error is first
inserted into a buffer and is stored in the buffer until it is not fully filled. or the buffer is not explicitly
flushed (using flush()). The error message will be displayed on the screen too.

#include <iostream>
using namespace std;
int main()
{
clog << "An error occured";
return 0;
}
#include <iostream>

using namespace std;

int main() {

char str[] = "Unable to read....";

clog << "Error message : " << str << endl;

return 0;

Loops in C++

Loops in programming come into use when we need to repeatedly execute a block of statements. For
example: Suppose we want to print “Hello World” 10 times.

In computer programming, a loop is a sequence of instructions that is repeated until a certain condition
is reached.

• An operation is done, such as getting an item of data and changing it, and then some condition
is checked such as whether a counter has reached a prescribed number.

• Counter not Reached: If the counter has not reached the desired number, the next instruction
in the sequence returns to the first instruction in the sequence and repeat it.

• Counter reached: If the condition has been reached, the next instruction “falls through” to the
next sequential instruction or branches outside the loop.

There are mainly two categories of loops:

1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry-controlled loops.

2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of
loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test
condition is true or false. do – while loop is exit controlled loop.
1. for Loop

A for loop is a repetition control structure which allows us to write a loop that is executed a specific
number of times. The loop enables us to perform n number of steps together in one line.

In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value,
then check whether this variable is less than or greater than counter value. If statement is true, then
loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.

• Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: int i=1;

• Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: i <= 10;

• Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: i++;

Syntax:

for (initialization expr; test expr; update expr)


{
// body of the loop
// statements we want to execute
}

Flow Diagram:
// C++ program to illustrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
return 0;
}

#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output

12345
Here is how this program works

Iteration Variable i <= 5 Action

1st i=1 true 1 is printed. i is increased to 2.

2nd i=2 true 2 is printed. i is increased to 3.

3rd i=3 true 3 is printed. i is increased to 4.

4th i=4 true 4 is printed. i is increased to 5.

5th i=5 true 5 is printed. i is increased to 6.

6th i=6 false The loop is terminated

// C++ Program to display a text 5 times


#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Output

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Here is how this program works


Iteration Variable i <= 5 Action

1st i=1 true Hello World! is printed and i is increased to 2.

2nd i=2 true Hello World! is printed and i is increased to 3.

3rd i=3 true Hello World! is printed and i is increased to 4.

4th i=4 true Hello World! is printed and i is increased to 5.

5th i=5 true Hello World! is printed and i is increased to 6.

6th i=6 false The loop is terminated

2. While Loop

While studying for loop we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loops are used in
situations where we do not know the exact number of iterations of loop beforehand. The loop execution
is terminated on the basis of test condition.

Syntax:

initialization expression;
while (test_expression)
{
// statements
update_expression;
}

Flow Diagram:
// C++ program to illustrate while loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}

3. do while loop

In do while loops also the loop execution is terminated on the basis of test condition. The main
difference between do while loop and while loop is in do while loop the condition is tested at the end of
loop body, i.e do while loop is exit controlled whereas the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.

// C++ program to illustrate do-while loop


#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout << "Hello World\n";

// update expression
i++;
} while (i < 1); // test expression
return 0;
}

4. What about an Infinite Loop?

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so
that it repeats indefinitely. An infinite loop occurs when a condition always evaluates to true. Usually,
this is an error.

// C program to demonstrate infinite loops


// using for and while
// Uncomment the sections to see the output
#include <stdio.h
int main ()
{
int i;
// This is an infinite for loop as the condition
// expression is blank
for ( ; ; )
{
printf("This loop will run forever.\n");
}
// This is an infinite for loop as the condition
// given in while loop will keep repeating infinitely
/*
while (i != 0)
{
i-- ;
printf( "This loop will run forever.\n");
}
*/
// This is an infinite for loop as the condition
// given in while loop is "true"
/*
while (true)
{
printf( "This loop will run forever.\n");
}
*/
}
Important Points:
1. Use for loop when number of iterations is known beforehand, i.e. the number of times the loop
body is needed to be executed is known.

2. Use while loops where exact number of iterations is not known but the loop termination
condition is known.

3. Use do while loop if the code needs to be executed at least once like in Menu driven programs

You might also like