Wednesday 20 February 2013

A program to print a maximum value in array


#include<iostream.h>
using namespace std;
main( )
{
float  abc[10], max;
int i;
for(i=0;i<=9;i++)
{
cout<<"enter values";
cin>>abc[i];
}
max=abc[0];
for(i=1;i<9;i++)
{
if(max<abc[i] )
max=abc[i];
}
cout<<max;
}

A program to calculate sum and average of array element


#include<iostream.h>
usinf namespace std;
main( )
{
float abc[4] ,  sum, avg;
int  i;
for(i=0;i<=3;i++)
{
cout<<"enter the value"<<i<<endl;
cin>>abc[i];
}
sum=avg=0.0;
for(i=3;i>=0;i--)
sum=sum+abc[i]
avg=sum/4.0;
cout<<sum<<endl;
cout<<avg;
}

A program to enter integer type value in array and then print the value in reverse order


#include<iostream.h>
using namespace std;
main( )
{
int  abc[4], i;
for(i=0;i<=3;i++)
{
cout<<"enter the values";
cin>>a[i];
}
cout<<"output in reverse order";
for(i=3;i>=0;i--)
cout<<abc[i]<<endl;
}

A program to declare an array and printing value that are added in array

#include<iostream.h>
using namespace std;
main( )
{
float a[4];
a[0]=9.7;
a[1]=12.5;
a[2]=1.9;
a[3]=2.1;
for(i=0;i<=3;i++)
cout<<a[i]<<endl;
}

Saturday 2 February 2013

file formation in c++



  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therefore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:

1
2
3
4
5
6
7
8
9
10
11
12
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
[file example.txt]
Writing this to a file.


This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do withcout, but using the file stream myfile instead.

But let's go step by step:

Open a file


The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::inOpen for input operations.
ios::outOpen for output operations.
ios::binaryOpen in binary mode.
ios::ateSet the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the fileexample.bin in binary mode to add data we could do it by the following call to member function open():

1
2
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary); 


Each one of the open() member functions of the classes ofstreamifstream and fstream has a default mode that is used if the file is opened without a second argument:

classdefault mode parameter
ofstreamios::out
ifstreamios::in
fstreamios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.

File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:

 
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);


Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

 
if (myfile.is_open()) { /* ok, proceed with output */ }


Closing a file

When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

 
myfile.close();


Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.

In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().

Text files

Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Data output operations on text files are performed in the same way we operated with cout:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
[file example.txt]
This is a line.
This is another line.


Data input from a file can also be performed in the same way that we did with cin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
This is a line.
This is another line.  


This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called good() that returns true in the case that the stream is ready for input/output operations. We have created a while loop that finishes when indeed myfile.good() is no longer true, which will happen either if the end of the file has been reached or if some other error occurred.

Checking state flags

In addition to good(), which checks whether the stream is ready for input/output operations, other member functions exist to check for specific states of a stream (all of them return a bool value): 

bad()
Returns true if a reading or writing operation fails. For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true.

In order to reset the state flags checked by any of these member functions we have just seen we can use the member function clear(), which takes no parameters.

Saving a File
One of the operations you can perform on a file consists of saving it, which is equivalent to storing its value(s) to a medium. To save a file, you can first declare an instance of theofstream class using one of its constructors from the following syntaxes:
ofstream();

ofstream(const char* FileName, int FileMode);
The default constructor allows you to initiate file processing without giving details. If you decide to use the default constructor, you can then call one of the methods we will see to perform the necessary operation. 
The ofstream(const char* FileName, int FileMode) constructor provides a complete mechanism for creating a file. It does this with the help of its two arguments. The first argument, FileName, is a string that specifies the name of the file that needs to be saved. The second argument, FileMode, specifies the kind of operation you want to perform on the file. It can be one of the modes we listed above.
Once you have decided what you want to do with a file, you use the << operator to save each value. Here is an example:

#include <fstream>

#include <iostream>

using namespace std;



int main()

{

    char FirstName[30], LastName[30];

    int Age;

    char FileName[20];



    cout << "Enter First Name: ";

    cin >> FirstName;

    cout << "Enter Last Name:  ";

    cin >> LastName;

    cout << "Enter Age:        ";

    cin >> Age;



    cout << "\nEnter the name of the file you want to create: ";

    cin >> FileName;

    ofstream Students(FileName, ios::out);

    Students << FirstName << "\n" << LastName << "\n" << Age;



    cout << "\n\n";

    return 0;

}
If you had used the default constructor to declare an ofstream variable, you can call theopen() method to actually process the file. The syntax of the open method is:
void open(const char* FileName, int Mode, int nProt = filebuf::openprot );
This method behaves exactly like, and uses the same arguments as, the constructor we described above. The first argument represents the name of the file you are dealing with and the FileMode argument follows the modes of the above table.

Because the fstream class in this case is declared as ofstream, the compiler is aware that you want to save a file (in reality, the use of ofstream means that you want to write to a file, in other words you want the FileMode with a value of ios::out), you can use the second constructor with just the FileName as argument or you can call the open() method with only the name of the file.
After using a file, you should close it. This is taken care by using the ofstream::close()method whose syntax is:
void close();

Opening a File
Besides saving, another operation you can perform consists of opening an already existing file to have access to its contents. To do this, C++ provides the ifstream class. Like ofstream, the ifstream class provides various constructors you can use, two of which are particularly important. If you have enough information about the file you want to open, you can use the following constructor:
ifstream(const char* FileName, int FileMode);
The first argument of the constructor, FileName, is a constant string that represents the file that you want to open. The FileMode argument is a natural number that follows the table of modes as we described above.
If necessary, you can also declare an empty instance of the ifstream class using the default constructor:
ifstream();
After declaring this constructor, you can use the ifstream::open() method to formally open the intended file. The syntax of the open() method is:
open(const char* FileName, int FileMode);
This method uses the same arguments as the above constructor. By default, when declaring an instance of the ifstream class, it is assumed that you want to open a file; that is, you want to use the FileMode attribute with a value of ios::in. Therefore, the second argument is already set to ios::in value. This allows you to call the open() method with just the FileName value.

After using the ifstream class, you can close it using the ifstream::close() method. Here is an example:
#include <fstream>

#include <iostream>

using namespace std;



int main()

{

    char FirstName[30], LastName[30];

    int Age;

    char FileName[20];

/*

    cout << "Enter First Name: ";

    cin >> FirstName;

    cout << "Enter Last Name:  ";

    cin >> LastName;

    cout << "Enter Age:        ";

    cin >> Age;



    cout << "\nEnter the name of the file you want to create: ";

    cin >> FileName;

    ofstream Students(FileName, ios::out);

    Students << FirstName << "\n" << LastName << "\n" << Age;

*/

    cout << "Enter the name of the file you want to open: ";

    cin >> FileName;

    ifstream Students(FileName);

    Students >> FirstName >> LastName >> Age;



 cout << "\nFirst Name: " << FirstName;

    cout << "\nLast Name:  " << LastName;

    cout << "\nEnter Age:  " << Age;



    cout << "\n\n";

    return 0;

}

String


There are mainly two types of handling strings such as using null terminated character arrays and using object of type string. The main drawback of null terminated strings is that most of the C++ operators cannot be applied on them. In order to overcome this drawback standard string class is used. If a string class is used normal operations can be performed on them like any other data type. When null terminated character arrays are declared memory space is wasted because you define the length of the array more than actually it is used. The use of string class does not waste memory space. In order to use string class header file <string> is included in the program. The general form of how string object is created is:-

            string object_name;

The object_name is the name of the object. For example,

            string name;

name is the object of type string. The operators which can be applied on object of string type are:-

            Operator                                              Meaning

                =                                                      Assignment
                +                                                      Concatenation
                +=                                                    Concatenation Assignment
                ==                                                    Equality
                !=                                                     Inequality
                <                                                      Less than
>                                                      Greater than
<=                                                    Less than or equal
>=                                                    Greater than or equal
[]                                                      Subscripting
<<                                                    Output
>>                                                    Input

Assignment

A string object can be assigned to another string object or another string. For example,

            string    name;
            string name1=”Peeyush”;
            name=name1;
                                   
objects name and name 1 will contain same string.

Concatenation

The two strings can be concatenated using ‘+’ operator. For example,

            string firstname=”Peeyush”;
            string lastname=”Taori”
            string fullname;
            fullname= firstname + “  “ + lastname;

The string objects firstname, whitespace and lastname are concatenated and assigned to string object fullname.

Equality

The equality operator ‘==’ checks whether the two strings are equal or not.

            string name1=”Peter”;
            string name2=”Peter”;
            if(name1==name2)
            {         
            }
The operator will return true because both string objects have same value.

Inequality

The inequality operator ‘!=’ returns true if two string objects are not equal. For example,

            string name1=”peter”;
            string name2=”Tom”;
            if(name1!=name2)
            {
            }
The operator will return true because name1 is not equal to name 2.

Less than

The less than operator checks whether the string objects come before another string object. It returns true if one string object in alphabetical order comes before another string object. For example,

            string name1=”cat”;
            string name2=”dog”;
            if(name1<name2)
            {         
                        cout << “cat comes before dog” << endl;
            }
The message “cat comes before dog” will be displayed as in alphabetical order word cat will appear before word dog.

Greater than

The greater than operator ‘>’ checks whether one string object comes after another string object. It returns true if one string object in alphabetical order comes after another string object. For example,

            string name1=”cat”;
            string name2=”dog”;
            if(name2>name1)
            {         
                        cout << “dog comes after cat” << endl;
            }

The message “dog comes after cat” will be displayed as alphabetically word dog comes after word cat.

Subscripting

The subscript operator ‘[]’ is used to access a character of the string just like null terminated character arrays. The subscript returns a char value. For example,

            string name1=”cat”;
            char ch=name1[1];
            name1[0]=’d’;

The character ch will contain letter ‘c’. The name1 will become will change to “dat”.

Input and Output
             
The insertion operator ‘<<’ writes the value of object to the output stream. The extraction operator ‘>>’ reads the character string from the input stream and assigns it to the string object. For example,
                       
string name;
                        cin >> name;
                        cout << name << endl;

The user will enter the name and the same name will be displayed on the screen.

Here is a program which shows the working of string class.

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

int main()
{
            char a,b;
            string name1,name2,name3;
            cout << "Enter your first name" << endl;
            cin >> name1;
            cout << "Enter your last name" << endl;
            cin >> name2;
            name3=name1 + "  " + name2;
            if(name1<name2)
            {         
                        cout << "First name alphabetically comes before last name" << endl;
            }
            if(name1>name2)
            {
                        cout << "Last name alphabetically comes before first name" << endl;
            }
            if(name1==name2)
            {
                        cout << "First name and last name are same" <<  endl;
            }
            cout << "Your full name is : " << name3 << endl;
            a=name1[0];
            b=name2[0];
            cout << "The initals of the name are " << a << "." << b << "." << endl;
            return(0);
}

The result of the program is:-

program output

The statement
           
            #include<string>

includes a header file string into the program. The statement
                       
            name3=name1 + "  " + name2;

concatenate two string objects and whitespace. The statement

                        if(name1<name2)

checks whether name1 alphabetically comes before name2. The statement

                        if(name1>name2)

checks whether name1 alphabetically comes after name2. The statement

                        if(name1==name2)

checks whether two string objects are equal or not. The statements

                        a=name1[0];
                        b=name2[0];

assign character a and b the first letter of name1 and name2 respectively.

ofstream


The ofstream is a file stream class. It is used for handling files. The ofstream is used to write data to different files at different times. To use ofstream header file fstream is included.  The insertion operator used to write data to a file. In order to write to a file an object of type ofstream 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 file to which data is to be written. The filename can contain the path where the file is stored. If no path is specified then current directory is considered. If the file does not exist then new file is created when object is created. The contents of the existing file are discarded when object is created. The file can be closed using close() function. Here is a program which illustrates the working of ofstream.

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

int main()
{
            char name[50];
            int age;
            ofstream outfile("D:\\outfile1.txt");
            cout << "Enter your name" << endl;
            cin >> name;
            outfile << name << endl;
            cout << "Enter your age" << endl;
            cin >> age;
            outfile << age << endl;
            outfile.close();
            return(0);
}

The result of the program is:-

program output



The statement

            #include<fstream>

includes a header file fstream in the program. The statement

            ofstream outfile("D:\\outfile1.txt");

creates an object outfile of type ofstream. The name of the file is outfile1.txt and its location is in D directory. The user enters his name and age. The statement
           
            outfile << name << endl;

writes the name of the user to the file. The statement

            outfile << age << endl;

writes the age of the user to the current file.