Thursday, July 30, 2009

C++ programming?

The following program is working properly with no error.





//***


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;fstream%26gt;


using namespace std;





void GetAndWrite(ifstream inFile);





int main()


{


ifstream inFile;


int number;





inFile.open("input.txt");


inFile %26gt;%26gt; number;


cout %26lt;%26lt; "number" %26lt;%26lt; " is " %26lt;%26lt; number;


}


//***





But when i want to pass the input file to a function, some errors happen. i mean the following program doesn't work.





//************************************...


#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;


#include %26lt;fstream%26gt;


using namespace std;





void GetAndWrite(ifstream inFile);





int main()


{


ifstream inFile;





inFile.open("input.txt");





GetAndWrite(inFile);


}





void GetAndWrite(ifstream inFile)


{


int number;


inFile %26gt;%26gt; number;


cout %26lt;%26lt; "number" %26lt;%26lt; " is " %26lt;%26lt; number;


}


//***





i used Dev-C++ compiler, but why the second program is not working?

C++ programming?
EDIT:


Make the argument to the function to be a POINTER not the ifstream object itself. Then it will compile and likely work.


In other words use:


void GetAndWrite(ifstream * inFile) // the argument is a pointer


{


int number;


*inFile %26gt;%26gt; number; //dereference the pointer


cout %26lt;%26lt; "number" %26lt;%26lt; " is " %26lt;%26lt; number;


}





int main()


{


ifstream inFile;





inFile.open("input.txt");





GetAndWrite(%26amp;inFile); //send a pointer into the function through the argument


}
Reply:It will be better if you pass olny the string to the function. Do not pass the file pointer. Then inside the function you can do same thing as you have done in first program.

blazing star

No comments:

Post a Comment