Write a C++ program which will accept ‘n’ integers from user through command line argument. Store Prime numbers in file “Prime.txt” and remaining numbers in “Others.txt”.

//Note: If you are not using Borland or Turbo C then add the following line after header files :
//using namespace std;

#include<stdlib.h>

#include<iostream.h>

#include<fstream.h>

#include<conio.h>

int main(int n, char * a[]) //n=no of arguments , a=arguments

{

    int x,i;

   cout<<"\nArguments are: ";

     for(i=1;i<n;i++)

     {

          cout<<a[i]<<" ";

     }

     ofstream f,f2;  //It represents output Stream and this is used for writing in files.

     f.open("prime.txt");

     f2.open("others.txt");

     for(i=1;i<n;i++)

     {   

         x=atoi(a[i]); //The atoi() function converts a character string to an integer value

          int flag=0;

          for(int j=2;j<=x/2;j++)

          {     

           if(x%j==0)

               {         

                  flag=1;

                    break;

               }

          }

          if(flag==0)

          {

                f<<x;

               f<<" ";

          }

  else

          { 

             f2<<x;

               f2<<" ";

          }

     }

     f.close();

     f2.close();

     ifstream fi; // ifstream object is used to open a file for reading purpose only.

     fi.open("prime.txt",ios::in);

     cout<<"\nContent of Prime File is: \n";

     char c;

     c=fi.get();

     while(!fi.eof())

     {  

         cout<<c;

          c=fi.get();

     }

     fi.close();  //close the file

     fi.open("others.txt",ios::in);

     cout<<"\nContent of Others File is: \n";

     c=fi.get(); // get() reads content in file

     while(!fi.eof()) // eof= end of file

     { 

          cout<<c;

          c=fi.get();

     }

     fi.close();

    getch();

    return(0);

}


0 Comments