Thursday, July 9, 2009

C++ reading from a file 'ifstream'?

We just made the transition from C to C++ and I have this method only file with this code to rad from a .txt file. when i compile it a message appears ('ifstream' undeclared 1st use in function) when i do the same using it in main it does work. how do i fix this? the data reading has to take place in a function. Yhank You!


#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;


int Flight::setData(Flight array[MAX], Flight *ptrArray)


{


ptrArray=array;


ifstream myfile ("example.txt");


if (myfile.is_open())


{


while (! myfile.eof() )


{


fp_in %26gt;%26gt; ptrArray-%26gt;flightAirline;


fp_in %26gt;%26gt; %26amp;ptrArray-%26gt;flightNumber;


fp_in %26gt;%26gt; %26amp;ptrArray-%26gt;stops;


cout%26lt;%26lt;flightAirline%26lt;%26lt;endl;


cout%26lt;%26lt;flightNumber%26lt;%26lt;endl;


cout%26lt;%26lt;stops%26lt;%26lt;endl;


}


myfile.close();


}


cout%26lt;%26lt;"End of reading\n"%26lt;%26lt;endl;


}

C++ reading from a file 'ifstream'?
put under your #includes





using namespace std;





You might want to check out C++ namespaces.





An alternate would be to do





using std::ifstream;


using std::endl;





and so on for each of the different variables/functions from the std namespace.
Reply:Try doing it like this instead.





ifstream myfile;


myfile.open("example.txt");


No comments:

Post a Comment