循环解释

Loop interpretation

我无法理解我在网上找到的这段代码的某些部分,它的目标是从 .txt 文件打印 ASCII 艺术作品。更准确地说,我在理解第 28 行中的 while 循环时遇到了麻烦,它是字符串函数“getFileContents”的一部分。 '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.";
    }
}

如果你看一下std::getline(),你会发现字符串参数是通过非常量引用传递的。这意味着字符串可以(并且正在)由 std::getline() 函数编辑。所以一行一行:

    // 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).
    }

之所以需要 TempLine 是因为 std::getline() 需要一些东西来读取文件内容,如果我们将 Lines 直接传递给函数,我们只会 return 文件的最后一行(前面的行总是会在字符串中被覆盖)。