0% found this document useful (0 votes)
19 views

UNIT 4.docx-c++

The document provides an overview of C++ stream classes, including the ios, istream, and ostream classes, which facilitate input and output operations. It also covers unformatted and formatted console input/output operations, exception handling using try, catch, and throw keywords, and the use of command-line arguments in C++. Key concepts such as the argc and argv variables for command-line arguments are explained with example code.

Uploaded by

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

UNIT 4.docx-c++

The document provides an overview of C++ stream classes, including the ios, istream, and ostream classes, which facilitate input and output operations. It also covers unformatted and formatted console input/output operations, exception handling using try, catch, and throw keywords, and the use of command-line arguments in C++. Key concepts such as the argc and argv variables for command-line arguments are explained with example code.

Uploaded by

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

UNIT 4

1.C++ Stream classes


In C++ there are number of stream classes for defining various streams
related with files and for doing input-output operations. All these classes are
defined in the file iostream.h.

1. ios class is topmost class in the stream classes hierarchy. It is the base class for
istream, ostream, and streambuf class.

2. istream and ostream serves the base classes for iostream class. The class istream is
used for input and ostream for the output.

3. Class ios is indirectly inherited to iostream class using istream and ostream. To
avoid the duplicity of data and member functions of ios class, it is declared as virtual
base class when inheriting in istream and ostream as

Syantax

class istream: virtual public ios

{
};

class ostream: virtual public ios

};

4. The withassign classes are provided with extra functionality for the assignment
operations that’s why _withassign classes.

5. The ios class: The ios class is responsible for providing all input and output
facilities to all other stream classes.
6.The istream class: This class is responsible for handling input stream. It provides
number of function for handling chars, strings and objects such as get, getline, read,
ignore, putback etc..
Example Program
#include <iostream>
using namespace std;

int main()
{
char x;

// used to scan a single char


cin.get(x);

cout << x;
}
2.C++ stream
C++ comes with libraries which provides us with many ways for performing input and
output. In C++ input and output is performed in the form of a sequence of bytes or
more commonly known as streams.
The most basic stream types are the standard input/output streams: istream cin.
built-in input stream variable; by default hooked to keyboard. ostream cout built-in
output stream variable; by default hooked to console.
● 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.

3.Unformatted I/O
It is a method of cin object used to input a single character from keyboard. But
its main property is that it allows wide spaces and newline character. It is a method of
cout object and it is used to print the specified character on the screen or monitor.
Unformatted Input/Output is the most basic form of
input/output. Unformatted input/output transfers the internal binary representation of
the data directly between memory and the file. Formatted output converts the internal
binary representation of the data to ASCII characters which are written to the output
file

Unformatted consol input output operations

1.void get()

It is a method of cin object used to input a single character from keyboard. But its
main property is that it allows wide spaces and newline character.

Syntax:

char c=cin.get();

2.void put()

It is a method of cout object and it is used to print the specified character on the screen
or monitor.

Syntax:

cout.put(variable / character);

3.getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with multiple spaces.

Syntax:

char x[30];

cin.getline(x,30);

4.write(char * buffer, int n)

It is a method of cout object. This method is used to read n character from buffer
variable.

Syntax:

cout.write(x,2);

5.cin

It is the method to take input any variable / character / string.

Syntax:
cin>>variable / character / String / ;

6.cout

This method is used to print variable / string / character.

Syntax:

cout<< variable / charcter / string;

4.Formatted console input output operations


The difference between formatted and unformatted input and output
operations is that in case of formatted I/O the data is formatted or
transformed. Unformatted I/O transfers data in its raw form or binary representation
without any conversions. ... putchar() function will print a single character on standard
output.

In formatted console input output operations we uses following functions to


make output in perfect alignment. In industrial programming all the output should be
perfectly formatted due to this reason C++ provides many function to convert any file
into perfect aligned format

1.width(n)

This function is used to set width of the output.

Syntax:

cout<<setw(int n);

2.fill(char)

This function is used to fill specified character at unused space.

Syntax:

cout<<setfill('character')<<variable;

3.precison(n)

This method is used for setting floating point of the output.

Syntax:
cout<<setprecision('int n')<<variable;

4.setflag(arg 1, arg,2)

This function is used for setting format flags for output.

Syntax:

setiosflags(argument 1, argument 2);

5. unsetflag(arg 2)

This function is used to reset set flags for output.

Syntax:

resetiosflags(argument 2);

6.setbase(arg)

This function is used to set basefield of the flag.

Syntax:

setbase(argument);

5.Exception Handling

An exception is a problem that arises during the execution of a program. A


C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.

Exception handling in C++ is built on three keywords: try, catch, and


throw. throw: A program throws an exception when a problem is detected which is
done using a keyword "throw". catch: A program catches an exception with
an exception handler where programmers want to handle the anomaly.

Exceptions provide a way to transfer control from one part of a program to


another. C++ exception handling is built upon three keywords: try,
catch, and throw.
● throw
throw keyword.
● catch

catch keyword indicates the catching of an exception.


● try try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using


a combination of the try and catch keywords
Syntax

try {

// protected code

} catch( ExceptionName e1 ) {

// catch block

} catch( ExceptionName e2 ) {

// catch block

} catch( ExceptionName eN ) {

// catch block

Throwing Exceptions

Exceptions can be thrown anywhere within a code block


using throw statement. The operand of the throw statement determines a type for the
exception and can be any expression and the type of the result of the expression
determines the type of exception thrown.

double division(int a, int b)


{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.

Try
{
// protected code
}
catch()
{
// code to handle ExceptionName exception
}

Example Program

#include <iostream>

using namespace std;

double division(int a, int b) {

if( b == 0 ) {

throw "Division by zero condition!";

return (a/b);

int main ()

int x = 50;

int y = 0;

double z = 0;

try {

z = division(x, y);

cout << z << endl;

catch (const char* msg)


{

cerr << msg << endl;

return 0;

Command Line Arguments in C++

Last Updated : 25 Jan, 2024

Command-line arguments are arguments that are passed to a program when it is executed
from the command line or terminal. They are provided in the command-line shell of
operating systems with the program execution command.

The main function of C++ generally can have the following signature:

int main(){

// Suitable Code

return 0;

But to pass command-line arguments, we typically define main() with two arguments, where
the first argument is the number of command-line arguments and the second is the list of
command-line arguments.

Signature of main() Function for C++ Command Line Arguments

int main(int argc, char *argv[]){


// Suitable Code
return 0;
}

What is argc?

The variable argc (ARGument Count) is an integer that stores the number of command line
arguments passed to the main function. It also includes the count for the name of the
program, so if we pass a value to a program, the value of argc would be 2 (one for argument
and one for program name).

What is argv?

The array argv (ARGument Vector) is an array of C-style strings like ('char*') where every
element points to a command line argument. argv does not store the actual argument, but the
pointer to that argument. The argv[0] will always contain the name of the program.

Example of Command Line Argument in C++

// C++ program to demonstrate the use of command line

// arguments

#include <iostream>

using namespace std;

int main(int argc, char* argv[])

cout << "You have entered " << argc

<< " arguments:" << endl;

// Using a while loop to iterate through arguments

int i = 0;

while (i < argc) {

cout << "Argument " << i + 1 << ": " << argv[i]

<< endl;

i++;

return 0;

Input
./program1 hello geeks

Output

You have entered 3 arguments:


Argument 1: ./program1
Argument 2: hello
Argument 3: geeks

Properties of Command Line Arguments in C++

 The argc is an integer that stores the number of command line arguments.

 The argv store is an array of pointers to characters that stores the command line
arguments.

 The first element in argv (argv[0]) contains the name of the program itself.

 Only string values are passed through the command line argument.

 Multiple arguments are separated by a whitespace. To pass a single argument with


some whitespace, we use

 The argv[1] points to the first command line argument and argv[argc-1] points to the
last argument. argv[argc] is NULL.

Command Line Arguments in Different Scenarios

The following programs illustrate the behaviour of C++ program for different kinds of
command line arguments.

Multiple Command Line Arguments

In the following program, we pass three arguments to the main function from the command
line.

// C++ program for passing multiple command line arguments

#include <iostream>

using namespace std;

int main(int argc, char* argv[])

if (argc >= 2) {
// printing number of arguments

cout << "Number Of Arguments Passed: " << argc

<< endl;

cout << "----Following Are The Command Line "

"Arguments Passed----"

<< endl;

// printing all the arguments

for (int i = 0; i < argc; ++i) {

cout << "argv[" << i << "]: " << argv[i]

<< endl;

return 0;

Terminal Command:

$ ./program one two three

Output:

Number Of Arguments Passed: 4


----Following Are The Command Line Arguments Passed----
argv[0]: ./program
argv[1]: one
argv[2]: two
argv[3]: three

Passing Space Seperated String as a Single Argument

In C++ program, multiple command line arguments are passed to the function by separating
them by a whitespace but what happens if you have to pass an argument string that already
contains spaces. In such case, we can enclose that string in the double quotes to pass it as a
single argument.
// C++ program to illustrate the spaces seperated string as

// a single argument

#include <iostream>

using namespace std;

int main(int argc, char* argv[])

cout << "Program Name Is: " << argv[0] << endl;

if (argc >= 2) {

cout << "Number Of Arguments Passed: " << argc

<< endl;

cout << "----Following Are The Command Line "

"Arguments Passed----"

<< endl;

cout << "argv[0]: " << argv[0] << endl;

cout << "argv[1]: " << argv[1] << endl;

return 0;

Terminal Command:

$ ./solution.out 'one two three'

Output:

Program Name Is: ./solution.out


Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./solution.out
argv[1]: one two three

You might also like