如何解决循环解释
我无法理解我在网上找到的这段代码的某些部分,它的目标是从 .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
传递给函数,我们只会返回最后一个文件的行(前面的行总是会在字符串中被覆盖)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。