Articles by "CPP"
Showing posts with label CPP. Show all posts
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Character-Oriented I/O

We have discussed token-oriented input, performed when you use the operator  >> on streams and file streams.  Token-oriented input reads a token, an item (generally) separated from the next token by whitespace characters. We have also discussed line-oriented input, performed by getline(), which reads an entire line of input.  C++ has a third kind of I/O, character-oriented I/O, which reads in or prints out one character at a time.  Character-oriented I/O is performed by the functions get() and put().

The get() Function
The  stream input function specifically designed for input of a single character value is get().  In its most common form, this function reads a single character (including a whitespace character; remember that whitespace characters are spaces, tabs and newline characters) from the keyboard and returns it.  Typically, the value returned is assigned to a variable of type char.  

The general form of a call to get() to read a character from an input stream infile into a variable ch:

ch = infile.get();

• The stream can be a file stream, like infile, or it can be cin.
• If it attempts to read past the end of input, the stream variable gets a value indicating failure.

Why Do We Need get()?
You might ask why we need the get() function, since the extraction operator >> is capable of reading a character from a stream. The answer is that the extraction operator will not read whitespace characters. Suppose you want to read all the characters in this line and count them:

This is the string.
If you were to read this string character by character with the >> operator and count the characters, you would read in 16 characters. If you were to read it character by character with get(), you would read in 19 characters, counting the spaces. (And if you were to read it with getline(), you'd read the whitespace characters, but you'd read the whole string at once; and you couldn't count the characters as they are being read in.) 

no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Data Type string::size_type

Many C++ string member functions return a numeric value which is not of type int.  The member functions size() and length() return a value which has type string::size_type. This is an unsigned integer type. (An unsigned integer can never be negative.) Suppose I want to store the length in a variable. I must declare the variable. It is more precise to declare it as type string::size_type rather than int. Note that to use this data type, size_type must be preceded by the word string and two colons:

string state = "New York";
string city = "Cincinnati";
string::size_type num1, num2 ;

num1 = state.length();  num1 is 8 (the space is counted)
num2 = city.size();     num2 is 10

Notes:
• We are using the names of the strings--state and city--to indicate what string object [variable] the member function should act upon. [to whom the function belongs?]
• It is safest to use string::size_type when referring to string sizes or to positions in a string.
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
String functions:

The string class is a pre-defined class. Think of it as a type like int or double.)  
Many pre-defined classes in C++ have functions associated with them, called methods or member functions of the class. Member functions define the operations that can be performed on [?by] objects of the class. We've already used several member functions of other classes: in Chapter 3, we introduced the iostream member functions cout.precision() and cout.width(). These member functions work on cout, which is an object of the iostream class. We also introduced the fstream member functions open() and close() which work on files, objects of the fstream class. 

A string variable is an object of the string class.  Among its most useful member functions are length(), substr(), find(), insert(), and erase().

The length of a string is the number of characters currently stored in the string.  There are two member functions that will return this value: length() and size(). (They do the same thing.)

To call a member function, we use dot notation:   object.method();  
You’ve seen
cout.precision()
cout.width()
   
Now we’ll have 
city.length()   

Example:
string city=”Queens”; 
cout << city.length(); 
Will print 6, the number of characters stored in city.
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
String operations: Concatenation and Comparing Strings

String operations in C++ are performed using some of the same operators that are used for arithmetic operations. The symbols are interpreted slightly differently in some cases. We've already seen the use of the = operator for assignment. 

Concatenating Strings:
It is possible to join two or more strings together using the + operator. Rather than addition, this use of the + operator joins one string to the end of another; this operation is called concatenation.
string str1, str2, str3;
str1 = "yesterday";
str2 = "morning";
str3 = str1+ " " + str2;
cout << str3 << endl; 
String str3 has the value "yesterday morning", and that value is sent to cout. 
Notes:
• It is necessary to concatenate a space between the two words to produce a space in the resulting string.  
• At least one of the operands must be a variable. [Useless to concatenate two literals.]
• The use of an operator (like +) for two different actions is called operator overloading. [not responsible this term]
string str = "train"; 
str = str + 's';
str has the value "trains". 
Note that it is also possible to use the += operator to perform concatenation:
str += 's';

Comparing Strings
You can compare two strings using the standard relational operators (<, <=, >, >=, ==, and !=). Two strings are the same (equal to each other) if they have the same number of characters and if each corresponding character matches: e.g., "cat" is the same as "cat" but not the same as "act", "Cat" or even as "cat " (with a space at the end). 
string str1 = "cat";
string str2 = "dog";
if (str1 == str2)
cout << "alike" << endl;
else
cout << "different" << endl;
   
This will, of course, print "different"  because "cat" is not the same string as "dog".  
Strings can be compared to determine whether one is greater than or less than the other. 
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Declaring, Initializing, Printing, and Reading Strings

Now we’ll learn to store string values. C++ has a string class. Think of it as a type like int or double. This class allows one to declare objects (which we will treat like variables of data type string) and provides methods (or member functions) for manipulating strings. To use strings, you must #include<string>. The string header file includes the prototypes for the string functions, just as cmath contains the prototypes for mathematical functions, and iostream contains the prototypes for I/O functions.

Declaring, Initializing, Printing, and Reading Strings:

#include <iostream>
#include <string>
int main()
{
string str1, str2;
str1 = "Hello";
str2 = "Harry";
cout << str1 <<  ",  " < <  str2 << endl;
return 0;
}
This will print "Hello, Harry" and go to a new line.

You can 
• Initialize a string in the declaration
• Assign the value of one string to another, 
• Send a string to cout 
• Read in a string from cin – don’t need to type the quotes

But cin stops reading as soon as a whitespace (space, tab, or newline) character is encountered. This is quite limiting if you want to read in someone's full name or a sentence. 

getline(input_stream, string_variable, delimiting_character);

getline() reads characters (including whitespace characters) from the input_stream into the specified string_variable until the delimiting_character is encountered. The third parameter is optional. If it is omitted, the default is the newline character.

string name;
    
getline(cin,name);
cout << name << endl;

reads until it encounters the newline (i.e. the user hits "Enter").  The ‘\n’ is read but not stored in name.
The optional third parameter can be any character used as a delimiter. getline() reads until it encounters the delimiter, which is not stored in the string.

string first, second;
    
getline(cin, first,',');
getline(cin, second,'D');

Thus, if the line typed in was "Hello, John Doe" followed by a newline character, first would get the value "Hello" and second would get " John ", including space before 'J' and the space after 'n'. Neither string would include the comma because that was the delimiter.

ignore() Warning, warning, warning: 
Not in the book, but necessary: if you try to use getline after >>, it will read whatever is left on the line, even if it is just a newline character. You have to use the function ignore() (in  <iostring>) to ignore the rest of the line and go to the beginning of the next line.

cin.ignore(numchars,char);
ignore() skips the number of characters specified or all of the characters up to and including the character specified by the second parameter, whichever comes first.
For example,

cin.gnore(80,’\n’);
skips 80 characters or goes to the beginning of the next line.
Use infile.ignore(100,’\n’); if you are reading from infile rather than the keyboard.
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Write a C++ program to illustrate exception handling concept using queue operation as an example.

Program Algorithm:
Step 1: Include the Header file.
Step 2: Create a class Stack which initializes size of the stack
Step 3: Create function push to do insert operation which in turn throws an exception when it overflow.
Step 4: Create function pop to do delete operation which in turn throws an exception when it underflows.
Step 5: Display the operation on the console using display function.

Program Code:
#include<iostream.h>
class queue
{
public:
int size;
int front ,rear;
int *a;
queue(int sz)
{
size=sz;
a=new int[sz];
front =-1;
rear=-1;
}
void insert(int c)
{
if(rear==size-1)
{
throw rear;
}
else
{
a[++rear]=c;
}
}
void remove()
{
if(front==rear)
throw 'u';
else
cout<<"\n"<<a[++front]<<" removed\n";
}
void display();
};
void queue::display()
{
cbout<<"\nQueue:\n";
for(int i=front + 1 ;i<=rear;i++)
cobut<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter queue size:";
cin>>sz;
queue s(sz);
try
{
do
{
cout<<"\nEnter choice:\n1 for insert\n2 for remove\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.insert(x);
break;
case 2:s.remove();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
}
catch(char c)
{
if(c=='u')
cout<<"\nUnderflow.";
}
return 0;
}

Sample Inputs and Outputs:
Enter the size of queue: 3
Enter choice:
1 for insert
2 for delete
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
2
3
2
Removed
2
2
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Write a C++ program to illustrate exception handling concept using stack operation as an example.

Program Algorithm:
Step 1: Include the Header file.
Step 2: Create a class Stack which initializes size of the stack
Step 3: Create function push to do insert operation which in turn throws an exception when it overflow.
Step 4: Create function pop to do delete operation which in turn throws an exception when it underflow.
Step 5: Display the operation on the console using display function.

Program Code:
#include<iostream.h>
class Stack
{
public:
int size;
int top;
int *a;
Stack(int sz)
{
size=sz;
a=new int[sz];
top =-1;
}
void push(int c)
{
if(top==size-1)
{
throw top;
}
else
{
a[++top]=c;
}
}
void pop()
{
if(top==-1)
throw top;
else
cout<<"\n"<<a[top--]<<" removed\n";
}
void display();
};
void Stack::display()
{
cout<<"\nStack:\n";
for(int i=0 ;i<=top;i++)
cout<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter stack size:";
cin>>sz;
Stack s(sz);
try
{
do
{
cout<<"\nEnter choice:\n1 for push\n2 for pop\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.push(x);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
else
cout<<"\nUnderflow";
}
return 0;
}


Sample Inputs and Outputs:
Enter the size of stack: 3
Enter choice:
1 for push
2 for pop
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
3
2
2
Removed
3
2
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
To write a C++ program to illustrate dynamic polymorphism using different shapes as an example.

Program Algorithm:
Step 1: Make a class area which has a method.
Step 2: Make subclasses to this which have constructors that will take in the value for the required fields and will compute the area and put it in one of the member variables.
Step 3: call the method defined in step 1, which is overridden in all the subclasses to show their respective areas.

Program Code:
#include<iostream.h>
class Circle;
class Rectangle;
class Square;
class Triangle;
class Trapezium;
class Area
{
protected:
float area;
public:
Area(float a)
{
area=a;
}
virtual void display()
{
}
};
class Circle:public Area
{
protected:
float ar;
public:
Circle(float a):Area( a)
{
ar=3.14*a*a;
}
void display()
{
cout<<"Area of Circle="<<ar;
}
};
class Rectangle:public Area
{
protected:
float ar;
public:
Rectangle(float a,float b):Area( a)
{
ar=a*b;
}
void display()
{
cout<<"Area of Rectangle="<<ar;
}
};
class Square:public Area
{
protected:
float ar;
public:
Square(float a):Area( a)
{
ar=a*a;
}
void display()
{
cout<<"Area of Square="<<ar;
}
};
class Triangle:public Area
{
protected:
float ar;
public:
Triangle(float a,float b):Area( a)
{
ar=0.5*a*b;
}
void display()
{
cout<<"Area of Triangle="<<ar;
}
};
class Trapezium:public Area
{
protected:
float ar;
public:
Trapezium(float a,float b):Area( a)
{
ar=0.5*(a+b);
}
void display()
{
cout<<"Area of Trapezium="<<ar;
}
};
int main()
{
cout<<"\nEnter radius of circle:";
int ra;
cin>>ra;
Circle c(ra);
cout<<"\nEnter length and breadth of rectangle:";
int a,b;
cin>>a>>b;
Rectangle r(a,b);
cout<<"Enter side of square:";
int sq;
cin>>sq;
Square s(sq);
cout<<"Enter height and base of circle:";
int h,ba;
cin>>h>>ba;
Triangle t(h,ba);
cout<<"Enter parallel sides's length of trapezium:";
int p,pt;
cin>>p>>pt;
Trapezium tr(p,pt);
Area *bptr[5];
bptr[0]=&c;
bptr[1]=&r;
bptr[2]=&s;
bptr[3]=&t;
bptr[4]=&tr;
bptr[0]->display();
bptr[1]->display();
bptr[2]->display();
bptr[3]->display();
bptr[4]->display();
return 0;
}


Sample Inputs and Outputs:
Enter radius of circle: 2
Enter length and breadth of rectangle: 4 6
Enter side of square: 2
Enter height and base of circle: 3 2
Enter parallel sides's length of trapezium: 3 3
Area of circle=12.56
Area of rectangle=24
Area of square=4
Area of triangle=3
Area of Trapezium=1.5
no image
This Blog is particularly related to different programming subjects. It helps students of MCA, BCA, B.Tech, M.Tech, M.Sc(IT), PGDCA.
Write a C++ program to illustrate virtual function implementation.

Program Code:
Step 1: Create a class base with a method marked as virtual.
Step 2: Create a subclass of the base called derived and redefine the method defined in step 1.
Step 3: Create an object pointer of type base and Create it point to an object of type base first and call the methods you had marked as virtual using -> operator.
Step 4: repeat the same steps but by making the pointer point to an object of the derived type now.

Program Code:
#include<iostream.h>
class base
{
public:
void display()
{
cout<<"\nDisplay base";
}
virtual void show()
{
cout<<"\nShow base.";
}
};
class derived:public base
{
public:
void display()
{
cout<<"\nDisplay derived";
}
void show()
{
cout<<"\nShow Derived.";
}
};
int main()
{
base b;
derived d;
base *bptr;
bptr=&b;
cout<<"\nbptr points to base\n";
bptr->display();
bptr->show();
cout<<"\n\nbptr points to derived.";
bptr=&d;
bptr->display();
bptr->show();
return 0;
}


Sample Inputs and Outputs:
bptr points to base
Show base
Display base
bptr points to derived
Show derived
Display derived