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

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

问题描述

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



首先,这不是一个家庭作业



我知道如何一次读一个字,但我不知道如何一次读一行,如何读取整个文本文件。



如果我的文件包含1000个单词,该怎么办?



我的文本文件名为(Read)包含以下内容:



我喜欢玩游戏
我喜欢阅读
我有2本书



这是我到目前为止所做的:

  #include< iostream> 
#include< fstream>

using namespace std;
int main(){

ifstream inFile;
inFile.open(Read.txt);

inFile>>

有没有可能的方法一次读取整个文件,而不是读取每一行或每个字

您可以使用 std :: getline : p>

  #include< fstream> 
#include< string>

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

还要注意的是,你最好只是用它的构造函数中的文件名来构造文件流,而不是明确打开(同样适用于关闭,只是让析构函数



有关 std :: string :: getline()的进一步文档可以在< a href =http://en.cppreference.com/w/cpp/string/basic_string/getline> CPP参考。



可能是最简单方法来读取整个文本文件只是为了连接这些检索的行。

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


I'm in a tutorial which introduces files (how to read and write from\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.

What if my file contains 1000 words? It is not practical to read each 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 separate?

解决方案

You can use 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).

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天全站免登陆