如何一次一行地读取文件或整个文本文件? [英] How to read a file line by line or a whole text file at once?

查看:71
本文介绍了如何一次一行地读取文件或整个文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm in a tutorial which introduces files (how to read from file and write to file)

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

First of all, this is not a homework, this is just general help I'm seeking.

我知道如何一次阅读一个单词,但我不知道如何一次阅读一行,也不知道如何阅读整个文本文件.

I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.

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

What if my file contains 1000 words? It is not practical to read entire file word after word.

我的文本文件名为读取";包含以下内容:

My text file named "Read" contains the following:

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

这是我到目前为止所完成的:

This is what I have accomplished so far:

#include <iostream>
#include <fstream>

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

  inFile >>

是否有可能一次性读取整个文件,而不是分别读取每一行或每个单词?

Is there any possible way to read the whole file at once, instead of reading each line or each word separately?

推荐答案

您可以使用 std :: getline :

#include <fstream>
#include <string>

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

还请注意,最好只在构造函数中使用文件名构造文件流,而不要显式打开(对于关闭也一样,只需让析构函数完成工作即可).

Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).

有关 std :: string :: getline()的其他文档可以在

Further documentation about std::string::getline() can be read at CPP Reference.

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

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

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');
}  

这篇关于如何一次一行地读取文件或整个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆