C++ 读取文件

标签 c++

在 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/

相关文章:

c++ - 反转字符串 C++

java - 返回在各种语言的函数中创建的数组和对象

c++ - 如何用非虚函数覆盖虚函数?

c++ - Qt 使用 isAutoRepeat() 处理 QPushButton Autorepeat() 行为

c++ - 什么是更好的做法?通过指针或标识符传递类成员?

java - 使用大多数 Java 代码制作可执行文件,但可能会添加另一种语言

c++ - 如果您有很多节点类型,则访问者模式

初始化值时的 C++ 用户输入

c++ - std::set 填充了 boost::variant 元素不能按后代排序?

c++ - 对象类型如何在编译时未知?