I'm having trouble in understanding some part of this code I've found online, its goal is to print ASCII art from a .txt file. To be more accurate, I'm having trouble in undesrstanding the while loop in line 28 which is part of the string function "getFileContents". What's the meaning of 'TempLine'?
#include <iostream>
#include <fstream>
#include <string>
std::string getFileContents (std::ifstream&); //Gets file contents
int main(int argc, char *argv[])
{
std::ifstream Reader ("File1.txt"); //Open file
std::string Art = getFileContents (Reader); //Get file
std::cout << Art << std::endl; //Print it to the screen
Reader.close (); //Close file
return 0;
}
std::string getFileContents (std::ifstream& File)
{
std::string Lines = ""; //All lines
if (File) //Check if everything is good
{
while (File.good ())
{
std::string TempLine; //Temp line
std::getline (File , TempLine); //Get temp line
TempLine += "\n"; //Add newline character
Lines += TempLine; //Add newline
}
return Lines;
}
else //Return error
{
return "ERROR File does not exist.";
}
}
If you take a look at std::getline()
, you can see that the string parameter is passed by non-const reference. This means that the string can (and is) edited by the std::getline()
function. So line by line:
// Loop until the file stream cannot read any more input.
while (File.good ())
{
// Create a new, empty string called `TempLine`
std::string TempLine;
// Read a line from `File`, and write it into TempLine.
std::getline (File , TempLine);
// Add a newline character at the end of the string.
TempLine += "\n";
// Add the line we just read from the file to the `Lines` string,
// which holds the full file contents.
Lines += TempLine; //Add newline
// Repeat until all lines have been read from the file (or the file
// becomes otherwise unreadable).
}
The reason TempLine
is needed is because std::getline()
needs something to read the file content into, and if we passed Lines
directly to the function, we'd only ever return the last line of the file (the previous lines would always get overwritten in the string).