Saturday, 2 February 2013

ifstream


The ifstream is a file stream class used for file handling. To use ifstream header file fstream is used. It is used for reading input from the file. In order to read from a file an object of type ifstream is created. The general form of how object is created is:-

ifstream object_name(“filename”);

The object_name is the name of the object created. The filename is the name of the file. For example,

            ifstream  userstream(“file1.txt”);

The userstream is the name of the object and file1.txt is the name of the file. When the object is created file is automatically open. There is no need of explicitly opening the file. An error might occur while opening the file such as the file may not be found. The status of the file can be checked using ‘!’ operator along with ifstream object or using is_open() which returns true if file is open. The data can be read from the file using the insertion operator ‘>>’. The end of file can be checked using eof() function. It returns true when end of file is encountered. Here is a program which illustrates the working of ifstream.

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

int main()
{
            ifstream stream1("D:\\file1.txt");
            char a[80];
            if(!stream1)
            {
                        cout << "While opening a file an error is encountered" << endl;
            }
            else
            {
                        cout << "File is successfully opened" << endl;
            }
            while(!stream1.eof())
            {
                        stream1 >> a;
                        cout << a << endl;
            }
            return(0);
}

The result of the program is:

program output

The statement

            #include<fstream>

includes a header file fstream for using ifstream class. The statement

            ifstream stream1("D:\\file1.txt");

creates an object stream1 of type ifstream. The file is file1.txt which is located in D directory. During the creating of this object file is open. The statement
           
            if(!stream1)

checks whether an error is encountered while opening a file. If a file is successfully open then it returns true and prints the message “File is successfully opened”. The statement

             while(!stream1.eof())

checks the whether the end of file is encountered. The while loop is terminated when end of file comes. The statement

            stream1 >> a;

uses an insertion operator to read text from file stream. The string a will contain the text. 

cout


The cout is built in stream for standard output on the screen. It inserts the sequence of characters into the standard output stream. The cout is defined in the header file iostream within the std namespace. The header file iostream contains the definition of cout. The compiler will give error if header file is not included in the program if cout is used. The objects are written to cout using insertion operator. The insertion operator is <<. It is also called output operator. For example,

            cout << “All work and no play makes Jack a dull boy” << endl;

will display message “All work and no play makes Jack a dull boy” on the screen. Let us consider another example which displays the value of expression.

#include<iostream>
using namespace std;

int main()
{
            int x=5;
            int y=6;
            cout << "The addition of two numbers" << endl;
            cout << x+y << endl;
            return(0);
}

The result is:-

program output

The statement
           
            cout << "The addition of two numbers" << endl;

displays the message “The addition of two number” on the screen. The keyword endl is used so that next characters are displayed from new line. The statement

              cout << x+y << endl;

displays the addition of two numbers 5 and 6 and result 11 is displayed on the screen. The expression is evaluated and result is displayed on the screen.
                       

Date and Time Functions


There are several functions that deal with time and date.  In order to perform these functions header file <ctime> is included into the program. The header file defines time related types such as clock_t, time_t and structure tm. The clock_t and time_t represent system time and date in the form of integer. The structure tm has data and time broken into elements. Some of the functions are:-

  • asctime() - The function asctime() returns the pointer to the string containing the date and time in readable format.

  • clock() - The function clock() returns the no of ticks since the calling program has been running. In order to convert no of ticks into seconds divide it by macroCLOCKS_PER_SEC which is defines in the header file <ctime>.

  • ctime() - The function ctime() converts the value of time_t to string.

  • difftime()-The function difftime() returns the difference in seconds between two times. It takes two arguments.

  • gmtime() - The function gmtime() returns a pointer to the broken down form of the time which is in UTC(Coordinated Universal Time) format. It converts time_t to tm structure as UTC time. If the system does not support UTC a null value is returned.

  • localtime()- The function localtime() returns a pointer to the broken down form of time_t into the form of tm structure as local time.

  • mktime() - The function mktime() converts tm structure to time_t.

  • time() - The function time() returns the current time. The function can be called using a NULL pointer or pointer to a variable of type time_t.

Here is a program which illustrates the working of time and date functions.

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

int main()
{
            time_t time1;
            time_t start1,end1,start2;
            struct tm * currenttime;
            time(&start1);
            currenttime=localtime(&start1);
            time1=time(NULL);
            float a=(clock());
            time(&start2);
            cout << "The no of hours since January 1 2006 : " << (time1/3600) << endl;
            cout << "The current time : " << ctime(&time1) << endl;
            cout << "The date and time : " << asctime(currenttime) << endl;
            cout << "The no of ticks since the program has been called : " << (clock()) << endl;
            time(&end1);
            cout << "The time lapse between two times : " << difftime(end1,start2) << endl;
            return(0);
}

The result of the program is:-

program output

The statement

            #include<ctime>

includes a header file <ctime>  into the program. The statements

            time_t time1;
            time_t start1,end1,start2;

declares variables time1,start1,end1 and start2 of type time_2. The statement

            struct tm * currenttime;

declares a pointer to the variable currentime of type tm structure. The statement

            time(&start1);

returns the current time of the system. The statement

            currenttime=localtime(&start1);

returns the localtime of the start1 into the form of tm structure. The statement

            time1=time(NULL);

returns the current time of the system. The statement

            cout << "The no of hours since January 1 2006 : " << (time1/3600) << endl;

displays the no of hours since January 1. The time1 is divided no of seconds in an hour. The statement

            cout << "The current time : " << ctime(&time1) << endl;

displays the string format of the current time. The statement

            cout << "The date and time : " << asctime(currenttime) << endl;

displays the current time and date in readable format. The statement

            cout << "The no of ticks since the program has been called : " << (clock()) << endl;

prints the no of ticks since the program has been called. The statement

            cout << "The time lapse between two times : " << difftime(end1,start2) << endl;

prints the time difference between end1 and start2.

Random Function


There are functions which are used to generate pseudo random numbers. In order to use these function header file <cstdlib> is included into the program. There are mainly two random functions in C++ such as rand() and  srand().

  • rand () -  The function rand() generates the sequence of pseudo random numbers. It generates the random number between 0 and RAND_MAX.  RAND_MAX is a constant defined in header file <ctdlib>. A series of non related numbers are generated each time the function is called.

  • srand() - The function srand()  uses the seed parameter  to set the starting point for the sequence of random numbers generated by the function rand().The parameter seed is unsigned integer. It is used to generate different sequences of pseudo random numbers by specifying different seed each time when the program is run. If the seed is not changed then the same sequence will be generated as pervious sequence when the program is run.

Here is a program which illustrates the working of random functions.

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

int main()
{
            int a,b,c,d;
            cout << "Enter the starting number" << endl;
            cin >> a;
            srand(a);
            b=rand()%RAND_MAX;
            c=rand()%200;
            d=rand()%10+200;
            cout << "The number between 0 and " << RAND_MAX  << " is : " << b << endl;
            cout << "The number between 0 and 10 is : " << c << endl;
            cout << "The number between 200 and 210 is : " << d  << endl;
            return(0);
}

The result of the program is:-

program output
The statement

            #include<cstdlib>
I
includes  a header file <cstdlib> into the program. The statement

            srand(a);

sets the starting point of the sequence of random numbers to the value of the variable a. The value entered by the user is 12. The statement

            b=rand()%RAND_MAX

returns the number between 0 and RAND_MAX. The statement

            c=rand()%200;

returns the random number between 0 and 200. The random number returned is 28. The statement

            d=rand()%10+200;

returns the random number between 200 and 210. The number returned is 202. The statement

            cout << "The number between 0 and " << RAND_MAX  << " is : " << b << endl;

displays the value of RAND_MAX and random number between 0 and RAND_MAX which is 77. . The value of RAND_MAX is 32767.          

Math Functions


The mathematical functions provide the functionality of automatically computing some of the functions such as trigonometric functions, hyperbolic functions, exponential and logarithmic functions and other miscellaneous functions. In order to use these functions header file <cmath> is included into the program. Some of the commonly used functions are:-

  • abs() – The function abs() returns the absolute value of integer parameter.

  • acos()  -The function acos() returns the arc cosine of the argument. The range of the argument is from -1 to 1. Any argument outside this range will result in error.

  • asin()- The function asin() returns the arc sine of the argument. The range of the argument is from -1 to 1. Any argument outside the range will result in error.

  • atan()- The function atan() returns the arc tangent of the argument.

  • atan2()- The function atan2()  returns the arc tangent of y/x. It accepts two arguments.

  • ceil()- The function ceil() returns the smallest integer which is not less than the argument.

  • cos() – The function cos() returns the cosine of the argument. The value of the argument must be in radians.

  • cosh() –The function cosh() returns the hyperbolic cosine of the argument.

  • exp()- The function exp() returns the exponential of the argument.

  • fabs()- The function fabs() returns the absolute value of floating point parameter.

  •  floor()- The function floor() returns the largest integer which is not greater than the argument.

  • fmod()- The function fmod() returns the remainder of floating point division of the two arguments.

  • log() – The function log() returns the natural logarithm of the argument. An error is encountered if the argument is negative or zero.

  • log10()- The function log10() returns base 10 logarithm of the argument. An error occurs if the argument is negative or zero.

  • pow()- The function pow() returns the base raised to the power.

  • sin()- The function sin() returns the sine of the argument. The value of the argument must be in radians.

  •  sinh()- The function sinh() returns hyperbolic sine of the argument.

  • sqrt()- The function sqrt() the square root of the argument. An error occurs if the value of the argument is negative.

  •   tan()- The function tan() returns the tangent of the argument. The value of the argument must be in radians.

  • tanh()- The function returns the hyperbolic tangent of the argument.

 Here is a program which illustrates the working of the math functions.

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

int main()
{
      double a=-0.707;
      double a1=(45.0*3.14)/180;
      double a2=2;
      double b=0.0;
      b=acos(a);
      cout << "The arc cosine of " << a << ": " << b << endl;
      b=asin(a);
      cout << "The arc sin of" << a << ": " << b << endl;
      b=atan(a);
      cout << "The arc tangent of  " << a << " : " << b << endl;
      b=ceil(a);
      cout << "The ceiling of " << a << " : " << b << endl;
      cout << "The floor of  " << a << " : " << floor(a) << endl;
      cout << "The cosine of " << a1 << " : " << cos(a1) << endl;
      cout << "The exponential of " << a2 << " : " << exp(a1) << endl;
      cout << "The log of " << a2 << " : " << log(a2) << endl;
      cout << "The base " << a2 << " raised to the power " << b << " : "  << pow(a2,b) << endl;
      cout << "The square root of " << a2 << "  :  " << sqrt(a2) << endl;
      return(0);
}

     

The result of the program is:-

program output

The statement

      #include<cmath>

includes a header file <cmath> into the file. The statement

      b=acos(a);

returns the arc cosine of argument a. The arc cosine of -0.707 is 2.35604. The statement

            b=asin(a);

returns the arc sine of argument  a. The arc sin of a -0.707 is -0.785247. The statement

            b=atan(a);

returns the arc tangent of argument a. The arc tangent of -0.707 is -0.615409. The statement

       b=ceil(a);

returns the ceiling of argument a. The ceiling of -0.707 is 0. The statement

            cout << "The floor of  " << a << " : " << floor(a) << endl;

displays the floor of argument a. The floor of -0.707 is -1. The statement

             cout << "The cosine of " << a1 << " : " << cos(a1) << endl;

displays the cosine of the argument a1. The cosine of 45 degrees is 0.707. The argument a1 contains the radian value of 45 degrees. The statement

            cout << "The exponential of " << a2 << " : " << exp(a1) << endl;

displays the exponential of argument of a2. The exponential of 2 is 2.19241. The statement
           
      cout << "The log of " << a2 << " : " << log(a2) << endl;

displays the logarithm of argument a2. The logarithm of 2.0 is 0.69. The statement

            cout << "The base " << a2 << " raised to the power " << b << " : "  << pow(a2,b);

displays the base a2 raised to the argument b. The base 2.0 raised to the power 0 is 1. The statement

            cout << "The square root of " << a2 << "  :  " << sqrt(a2) << endl;

displays the square root of the argument a2. The square root of 2.0 is 1.414.
           

String Functions


The string functions can analyze and transform null terminated strings.  In order to manipulate null terminated strings header file <cstring> is included in the program. This header file provides the same functionality as string.h in C. Some of the commonly used string functions are: -

  • strcat(s1, s2) - It concatenates two strings. It concatenates s2 at the end of s1.
  • strcmp (s1, s2) – It is used to compare strings. It returns 0 if they are equal and less than 0 if s1<s2 and greater than 0 if s1>s2.
  • strlen(s1) – It returns the length of the string s1.
  • strcpy(s1, s2) - It copies s2 into s1.
  • strncat(s1, s2, n) -   It appends substring to the string. It takes first n characters of string s2 and appends s1.
  • strncmp(s1,s2,n) – It compares first n characters of string s1 with first n characters of string s2.
  • strchr(s1, ch) – Finds character ch in string s1.  It returns the pointer at the first occurrence of ch.
  • strstr(s1, s2) – Finds substring s2 in s1. It returns a pointer at the first occurrence of s1.

Here is a program which illustrates the working of string functions.

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

int main ()
{
      int l;
      char name[40]=" Tom is a good boy";
      char name1[40]="Mary is a good girl";
      char stri[40];
      l=strlen(name);
      cout << "The lenght of the string 1 is : " << l <<  endl;
      if(strstr(name,"good"))
      {
                  cout << "Substring good appears in string 1 " << endl;
      }
      if(strchr(name1,'M'))
      {
                  cout << "Character M appears in sting 1 " <<  endl;
      }
      if(strcmp(name,name1)>0)
      {
                  cout << "String 2 appears after string" << endl;
      }
      strcpy(stri,name1);
      cout << "The copied string  : " << stri << endl;
      strncat(stri,name,4);
      cout << " The modified string : " << stri << endl;
      if(strncmp(stri,name1,3)==0)
      {
                  cout << "First 3 characters of two strings are equal" << endl;
      }
      strcat(name,"  ");
      strcat(name,name1);
      cout << name << endl;
      return(0);
     
}

The result of the program is:-

program output

The statement

#include<cstring>

includes a header file <cstring> into the program. The statement

       l=strlen(name);

computes the length of the string name. The function strlen(name)  returns the length of the string name. The length of the string is 18. The statement

      if(strstr(name,"good"))

checks whether substring “good” appears in the string name. The function strstr(name,”good”) returns true as “good” appears in string name. The statement
     
      if(strchr(name1,'M'))

checks whether character ‘M’ appears in string name1. The function strchr(name1,’M’) returns true as character ‘M’ appears in string name1. The statement

                        if(strcmp(name,name1)>0)

compares two strings name and name1. It returns false as string name< string name1.
The statement

      strcpy(stri,name1);

copies content of string name1 into string stri. The statement

            strncat(stri,name,4);

concatenates first 4 letters of string name to string stri. The statement

            if(strncmp(stri,name1,3)==0)
     
compares first  3 characters of string name1 with first 3 characters of string stri. It   returns true as first 3 characters of name1 and stri are same. The statement

      strcat(name,"  ");

concatenates whitespace at the end of the string name. The statement

            strcat(name,name1);

concatenates content of string name1 at the end of  string name.