c++ - 如何逐行读取文件或一次读取整个文本文件?

标签 c++ iostream fstream file-handling

我在一个介绍文件的教程中(如何从文件中读取和写入文件)

首先,这不是作业,这只是我寻求的一般帮助。

我知道如何一次读取一个单词,但我不知道如何一次读取一行,或者如何读取整个文本文件。

如果我的文件包含 1000 个单词怎么办?逐字阅读整个文件是不切实际的。

我的名为“Read”的文本文件包含以下内容:

I love to play games
I love reading
I have 2 books

这是我迄今为止所取得的成就:

#include <iostream>
#include <fstream>

using namespace std;
int main (){
   
  ifstream inFile;
  inFile.open("Read.txt");

  inFile >>

有没有办法一次读取整个文件,而不是单独读取每一行或每个单词?

最佳答案

你可以使用 std::getline :

#include <fstream>
#include <string>

int main() 
{ 
    std::ifstream file("Read.txt");
    std::string str; 
    while (std::getline(file, str))
    {
        // Process str
    }
}

另请注意,最好只在构造函数中使用文件名构造文件流,而不是显式打开(关闭也是如此,只需让析构函数完成工作即可)。

更多关于 std::string::getline() 的文档可以在 CPP Reference 阅读。 .

可能读取整个文本文件的最简单方法就是连接那些检索到的行。

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  

关于c++ - 如何逐行读取文件或一次读取整个文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035674/

相关文章:

c++ - 在非静态成员函数错误之外无效使用 'this'?

c++ - 创建一个 const shared_ptr<pure virtual class> 成员

c++ - 使用预处理器指令定义命令行选项

double 类型的 C++ 变量总是将它们的值更改为 -9,25596e+061

c++ - 从文件读取到特殊字符

c++ - 你如何在 C++ 中搜索文档中的字符串?

c++ - 想逐行阅读,但 fstream 只读第一行

c++ - 另一种复制算法

c++ - 尝试将 vector <int>保存在bin文件中并读取它给出了随机数据

c++ - 自定义数据 iostream