C++ File Processing

October 27, 2015 Posted by WithU Technologies
We will learn to read and write files from C++ in this chapter.

To do that, first of all we need to include a header file from Standard C++ Library named fstream.

fstream is combined with two data separate library files which are:
·         ofstreamOutput file stream that creates and writes information to files.

·         ifstream -  Input file stream that read information from files.

So, before we input some text within a text file, we need to open that file.

And after that we can write something on that file.

Example:

#include<iostream>
#include<fstream>
using namespace std;

int main(){

ofstream NewFile;

NewFile.open("example.txt”);

NewFile<<"New Line added\n";

NewFile.close();

return 0;

}

·         This program will include fstream as header file.

·         Then it calls ofstream to create a new file. The file will be opened or created using open function.

·         And then it names that file within parentheses and double inverted commas (If a file with the same name is already stored in the project directory then it will open that one).

·         After that it writes something on that txt file and save it and then it closes that file using close function.


Opening a file by providing a path:

Instead of creating a new object and calling open function from ofstream library we can directly specify the file directory path by using ofstream object constructor.

int main(){

ofstream NewFile("f:\\example.txt");

NewFile<<"New Line added";

NewFile.close();

return 0;

}

There are various open modes which are used to indicate, what to do the file (eg. open, close) and the data (eg. Read, write). Some of the modes are described below:



Basic codes for file processing:

  • To read a file which is already existed:
ifstream  fileRead;

  • To write something in a newly opened file, or a file which is already existed:
ofstream  fileWrite;

  • To open a file in the same project folder for reading (Here example.txt is the filename):
FileRead.open("example.txt ");

  • To open a file in the different folder for reading (Here example.txt is the filename):
FileRead.open("d:\\example.txt ");

  • To opening a file for reading in binary type modes, we could write:
FileRead.open("example.txt ", ios::in | ios::binary);

  • To open a file and then seek to the end of that file, we could write like this:
FileRead.open("example.txt ", ios::in | ios::ate, 0);

  • To open a file for writing and appending at the end of the output file, we could write like this:
FileWrite.open("example.txt", ios::out | ios::app);

  • To check that the given name is already existed for a file within the same folder, we could write like this:
theoutputfile.open("example.txt", ios::out | ios::nocreate, 0);

  • To free up the resources to be used by other processes or programs.  Using the close() member function to close a function declared already, for input stream we would write like this:
FileRead.close();

  • And for output stream:
Filewrite.close();
·         Here FileRead and FileWrite are just objects to call functions, you can change them to any suitable word.

C++ Exceptions

October 27, 2015 Posted by WithU Technologies
There are several problems that occur during program execution or after user input which will crash or terminate the program without any clue for that if we do not apply exceptions handling methods to handle those exceptions.

C++ exceptions is built with three keywords:

try{

throw

catch(){

}

try – try block is used before the block of code where exceptions may generate after execution. It will activate those specific exception part within the program.

throw – throw keyword is used to throw an exception when problems show up along with a value which will be used as error value.

catch – It executes when a particular exception is thrown. You can make a simple output without any error code. But if we still want an error code then a value will be thrown by the throw keyword which will be pass through catch parameter and then executed with message.   
Example:

#include<iostream>
using namespace std;

int main(){

try{   //identifies a block of code that will activate specific exceptions

int n,a=0;

cout<<"Enter your mobile number: ";

cin>>n;   //user input stored in local variable n

while(n>0)  //while loop continues until the n value <  0

{

n=n/10;  //we divide n by 10

a++;    //and after each loop we increase a which is initialized from 0

}

      if(a!=10){      //if the number of digits in mobile number is not equal to 10

            throw 99;    //throw an exception with value of 99 for example

      }

      cout<<"Your mobile number is accepted"<<endl;  //if the number of digits is equal to 10 then this message will be displayed

}

      catch (int x){    //execute to catch the thrown exception and make an output on that with parameter to catch the exception value

            cout<<"Please enter your 10 digits mobile number Error-"<<x<<endl;  //you can also create a simple output without using the error number

      }

return 0;

}

·         A simple program is created above to take input of your mobile number.

·         After that we will calculate the number of digits entered by user.

·         We use while loop to calculate that. Here while loop is looped until the total digits entered by user will be less than 0

·         Inside the while loop we divide the n value by 10 which will exclude each digit from the total number entered by user.

·         And after each exclusion of digit, it will increment the value of variable a which is already initialized with 0.

·         Thus if the user inputted mobile number contains 10 digits then it will output “Your mobile number is accepted”.

·         And if the number of digits is not equal to 10 then it will throw an exception with an example error value of 99.

·         The exception is then caught by the catch keyword along its value and then it makes an output using that value.

 Here the catch handles integer type exceptions. But we can specify that our catch block handles any type of exceptions thrown by a try block.

And for that we use ellipsis between parentheses (…) of catch.

try{
      //Some block of Code

throw;

}

catch(...){  //ellipsis are used to handle any data type

      //Code to handle Exceptions with any data type 
}

C++ Template Specialization

October 27, 2015 Posted by WithU Technologies
When we use regular templates for functions or classes. The
templates handle different data types in the same way as the same code is used
for compilation of all data types.

But in case we need a specific data type for a particular argument or parameter.
We use the method of Template specialization where we override the default template implementation to handle a particular type in a different way.

It allows for the definition of a different implementation of a template when a specific type overrides the regular template argument.

Class template specializations are treated as completely independent classes, even though they are allocated in the same way as the template class.

This means that we can change anything and everything about our specialization class, including the way it’s implemented and even the functions it makes public, just as if it were an independent
class.


A specialized template initialized without any parameters
like:

template<>   

The particular parameter for that template is declared after
the class name during initialization. 

class show<char>{  

This specialization parameter itself identifies
the type for which the template class is being specialized.

And after that the specified data type is used
throughout the specified template class.

Example:

#include <iostream>
using namespace std;

template<class R>  //at first we declared the regular
template with a parameter R

class show {   //Class
declared


public:

  show(int a) {   //Constructor initialized
with a parameter

            if(a==2483){            //if statement is used to generate an
output based on user input, which is an integer

                  cout<<"You are right!"<<endl;

                  }

                  else{

                        cout<<"You are wrong!"<<endl;

                  }

            }

};

template<>    //Specialized
template is initialized without any parameters

class show<char>{   //Data type is
declare just after the same class name, which is declared earlier with regular
template

public:

      show(char a){   //Constructor also use that specialized
data


            //if statement
is used to generate an output based on user input, which a character

            if(a=='T' || a=='t'){

            cout<<"You are right!"<<endl;

            }

            else{

                  cout<<"You are wrong!"<<endl;

            }

      }

};

int main() {

    int s;    //local
variable initialized

      cout<<"Enter
your Choice? \n Question 1\n Question 2"
<<endl;   //to choose an
one question we implement if statements

      cin>>s;

      if(s==1){

            char x;

                          cout<<"Only 8%
of the world's currency is physical money, the rest only exist on
computers."
<<endl;

                              cout<<"(Enter T/F for True or
False)"
<<endl;

                              cin>>x;

                              show<char>Newob1(x);   //Char data type is also mentioned
here after class name and argument x is passed

      }

      if(s==2){

            int y;

            cout<<"Jerry sells mangoes in the
market. \nFirst day he sells 1458 apples. \nSecond day he sells 1025 apples. \nOn
the third day, he sells 126 less than the second day. \nHow
many apples are sold in three days "
<<endl;

            cin>>y;

            show<int>Newob2(y);
//int data type is also
mentioned here after class name and argument y is passed

      }

      return 0;

}


Here in the example given above a simple program
is written where at first we ask the user to choose any one question from two.

After that we provide the selected question and
took input from user and then generate an output according to that.

First of all, a regular template is initialized
to generate output based on integer datatype which is already learned by us.

But then we declared a specialized template with
the same class name to distinguish the regular template used for integers from
characters specialized template.

And we used the character specialized template
ta take a character input from user and output result according to that.

C++ Class Templates

October 27, 2015 Posted by WithU Technologies
As like the function templates we can define a class template with the help of same syntax we learned in the previous chapter.

 Example:
#include <iostream>

using namespace std;

template<class R>    //alternative template<typename R>

class DisplayGreater{

private:

  R a,b;   //two generic private member variables declared

public:

  DisplayGreater(R x, R y)   //constructor is used to initialize the variable

       :a(x), b(y)    //member list initialized

  {

  }

  R Display(){

        return (a>b?a:b);  //ternary operator is used

  }

};

int main() {

      DisplayGreater<int> show(10,25);  //data type is specified in angle brackets

      cout<<show.Display();     //Display function called

      return 0;

}

// Output 25

·         Here before declaring the class DisplayGreater we initialize the template.

·         Then we initialize two generic variables under private access specifier.

·         Those variables are then accessed by constructor and initialize them by member initializer list.

·         Then we create Display function with data type as R.

·         And then we used the ternary operator to find out the bigger value.

·         The ternary operator syntax provided here is (a>b?a:b) which is equivalent to the expression if a is greater than b, return a, else, return b.

·         In the main function we create an object named show using a different syntax.

·         In this case after the class name, datatype is specified within angle brackets in which the function works and make output.

·         The Display function returns the greater value of the two member variables.

Class templates for separate class files.

·         We already learn how to create separate header and source file for a new class and we also work with them.

·         So, now we learn how to implement or use the class template with separate class file.

·         A specific syntax is required in case we define our member functions outside of our class.

Example:

Header file (classname.h)
  template<class R>    //alternative template<typename R>

  class DisplayGreater{

  private:

  R a,b;   //two generic private member variables declared

  public:

  DisplayGreater(R x, R y)

       :a(x), b(y)    //member list initialized

  {

  }
  R Display();   //Declares the class        

Source file (classname.cpp)
template<class R>

R DisplayGreater<int>::Display()   //Defines the class and data type is specified in angle brackets

{

        return (a>b?a:b);  //ternary operator is used

}

C++ Function Templates

October 27, 2015 Posted by WithU Technologies
Till now we already work with many functions and in every program there is at least one default function i.e. the main function.

As you know that we have declare a return type and parameters to declare a function.
Example:

#include <iostream>

using namespace std;

int show(int a){

      return a;

}

int main() {

      int x = 5;

      cout<<show(x);

      return 0;

}

// Output 5

·         If we go through the example given above, we will find out that till now we have to limit C++ functions to certain data types which we have to declare earlier before compilation.

·         And if we need the same program written above in any other return type like float then we need to write the same code again by changing it’s return type to float as shown below:

float show(float a){

      return a;

}

……………………………….
·         But with the help of Function Templates we can write one version of function to work with parameters and return of any type.

·         As Function Templates does not specify any particular data type.

·         Function Templates use Placeholders to define a functions and its parameters called template type parameters.

Syntax:

      template <class template variable name>

                or

    template <typename template variable name>

Before declaring the function, template keyword is used followed by class or typename keyword along with the template variable name within angle brackets to declare the function template.


#include <iostream>

using namespace std;

template<class R>    //alternative template<typename R>

 R show(R a, R b){

      return a*b;

}

int main() {

      cout<<show(12.5,5.4);

      return 0;

}

// Output 67.5

·         Compiler automatically calls the function for its corresponding type.

·         Function templates help to reduce code maintenance, because duplicate code is reduced significantly.  

·         They work with every data types and thus we need to write redundant codes once at a time only.

Function Templates with Multiple Parameters:

Function templates can also be applied for multiple parameters of varying types.
#include <iostream>

using namespace std;

template<class R, class S>    //alternative template<typename R>

 R DisplayGreater(R a, S b){

      return (a>b?a:b);     //Ternary operator is declared

}

int main() {

      int x = 18.23;

      float y = 16.3;

      cout<<DisplayGreater(x,y);

      return 0;

}

// Output 18
·         We declare two different generic data types R and S.

Ternary operator
·         Ternary operators work like If statements. It checks the a>b condition and then provide the corresponding result.

·         The ternary operator syntax provided here is (a>b?a:b) which is equivalent to the expression if a is greater than b, return a, else, return b.

R DisplayGreater(R a, S b)


·         As we can see here that the return type of the function is R and according to the main function R takes X value which is an integer, thus R is also an integer.

·         So, the result we generate is also an integer and thus it only outputs 18.