在 C++ 中读取文件并将其内容分配给字符串所需的最少代码是多少? 我确实阅读了很多有用的教程,但它们在某种程度上都是不同的,所以我试图找出原因,所以如果你可以的话,请包括一些很好的解释性评论。
相关: What is the best way to read an entire file into a std::string in C++?
最佳答案
#include <fstream>
#include <string>
int main()
{
std::ifstream file("myfile.txt"); // open the file
std::string line, whole_file;
// Read one line at a time from 'file' and store the result
// in the string called 'line'.
while (std::getline(file, line))
{
// Append each line together so the entire file will
// be in one string.
whole_file += line;
whole_file += '\n';
}
return 0;
// 'file' is closed automatically when the object goes out of scope.
}
这里有几点需要注意。 getline()
返回对流对象的引用,如果发生任何错误或到达文件末尾,该对象将无法通过 while-test。此外,尾随的换行符不包含在字符串中,因此您必须手动附加它。
关于C++ 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/841464/