Hi! I'm new to C++ and am having a problem with saving a text file into a string. I'm using getchar() but only the last line of the rather long text file is saved into the string when used in different functions. In other words, if I include a "cout" that prints the string in main, after the functions, only the last sentence of the text file will be printed.

Would be truly grateful if someone could give me a push in the right direction. The following functions are featured in main() in the same order as the following two function definitions:

string fileName(string &file_name)
{
       cout << "Name of file:\n";
       cin >> file_name;
       int temporary=file_name.rfind(".txt");
       if (temporary == string::npos)
       file_name.append(".txt"); 
       return file_name;
}

void readFile(string &line, string &file_name)
{
     ifstream fin(file_name.c_str() );

     if(!fin)
     {
             cout << "No file with that name available " << file_name << endl;
             exit(EXIT_FAILURE);
                   }
while (!fin.eof())
{
while (getline(fin, line))
{

}
}
}

Best,
John

This loop is wrong:

while (!fin.eof())
{
  while (getline(fin, line))
  {

  }
}

First, the outer condition is good, it means you want to read until the end of the file. The problem it that inside, you are reading all the lines in a loop and always overwriting the string "line" (maybe you thought they would get appended to the "line", but it overwrites it completely every time). So, of course, at the end, you will get only the last line that was read from the file.

This should fix it:

while(!fin.eof()) {
  string next_line = "";  //create a temporary to hold the next line to read.
  getline(fin,next_line); //read the next line.
  line += next_line;      //and append it to "line".
};

Thanks so much! This actually makes sense now! Have a nice day!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.