Sunday, June 5, 2016

Files in C++

Hello reader, today my tutorial is about Files in C++. We use Files in C++ to add values to programme to outer source.

     Imagine we have an outer file called "data.txt" and it has two value 10 and 20. We need to add this value to our c++ programme.



  •      So do that first we need to declare the header file like this,

             #include<fstream>


  •      We can open our outer source file using following command,

             ifstream abc(data.txt)


  •      Also if you want to check your given File name (data.txt) is correct you can use following statements,

             If(abc.fail)
               {
                   cout<<"Error"<<endl;
                      return -1;       
               }

     Using all of these methods you can write successful programme like this,

#include<iostream>

#include<fstream>
using namespace std;
int main()
{
    int no1, no2;
    
    //input data.txt
    ifstream abc(data.txt);

    //check the output file

    if(abc.fail())
      {
        return -1;
      }

    //assign output files to variables

    abc>>no1;
    abc>>no2;

    cout<<no1<<" "<<no2<<endl;


 return 0;

}     

By - nisalsworld

No comments:

Post a Comment