Here is a more detailed explanation of my problem: I have a function that reads characters from a file and inputs them into a string that is within the scope of the function. Though, after inputing the information into the string and exiting the while loop, I return the string to another string, but I get 0, or no characters from the string that should have been holding that return value of my file reading function. After using gdb, and putting cout statements here and there, I finaly got my function to return the proper string. I have to return from the function from within the loop that reads from file and inputs into the local string. That contradicts from what I have understood variables in a local function to do. I thought that if I had the variable within the function It would not be destroyed UNTIL I exit from that scope, unless I threw it into heap and/or had a pointer, or made the variable global. Here is the code that should have worked, followed by the one that does work:
Code:
string ReadFromFile()
{
string fromfile;
ifstream rfile ( "example.txt" );
if ( rfile == 0 )
{ cout << "Failed to open \"example.txt\"! Exit failure!\n"; exit(-1); }
if ( rfile.is_open() )
{
while (! rfile.eof() )
{
getline(rfile,fromfile);
}
rfile.close();
}
else { cout << "\"example.txt\" is not open! Exiting failure?!\n"; }
return fromfile;
}
Code:
string ReadFromFile( )
{
string fromfile;
ifstream rfile ( "example.txt" );
if ( rfile == 0 )
{ cout << "Failed to open \"example.txt\"! Exit failure!\n"; exit(-1); }
if ( rfile.is_open() )
{
while (! rfile.eof() )
{
getline(rfile,fromfile);
return fromfile;
}
rfile.close();
}
else { cout << "\"example.txt\" is not open! Exiting failure?!\n"; }
return 0;
}
I compiled with the following if anyone is wondering:
Code:
g++ -g IOFile.cc -Wall -Wextra -o IOFile
Thank you in advance!