逐行读取文件 [英] Read file line by line

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

问题描述

file.txt的内容是:

  5 3 
6 4
7 1
10 5
11 6
12 3
12 4

其中 5 3 是一个坐标对。
如何在C ++中逐行处理这个数据?



我可以得到第一行,但是如何获得第一行文件?

  ofstream myfile; 
myfile.open(text.txt);


解决方案

  #include< fstream& 
std :: ifstream infile(thefile.txt);

这两种标准方法是:


  1. 假设每行由两个数字组成,并通过令牌读取令牌:

      int a ,b; 
    while(infile>> a>> b)
    {
    // process pair(a,b)
    }


  2. 使用字符串流进行基于行的解析:

      #include< sstream> 
    #include< string>

    std :: string line;
    while(std :: getline(infile,line))
    {
    std :: istringstream iss(line);
    int a,b;
    if(!(iss>> a>> b)){break; } //错误

    //进程对(a,b)
    }


你不应该混合使用(1)和(2),因为基于令牌的解析不会换行,如果您在使用基于令牌的提取之后使用 getline(),您就可以使用空行。


The contents of file.txt are:

5 3
6 4
7 1
10 5
11 6
12 3
12 4

Where 5 3 is a coordinate pair. How do I process this data line by line in C++?

I am able to get the first line, but how do I get the next line of the file?

ofstream myfile;
myfile.open ("text.txt");

解决方案

First, make an ifstream:

#include <fstream>
std::ifstream infile("thefile.txt");

The two standard methods are:

  1. Assume that every line consists of two numbers and read token by token:

    int a, b;
    while (infile >> a >> b)
    {
        // process pair (a,b)
    }
    

  2. Line-based parsing, using string streams:

    #include <sstream>
    #include <string>
    
    std::string line;
    while (std::getline(infile, line))
    {
        std::istringstream iss(line);
        int a, b;
        if (!(iss >> a >> b)) { break; } // error
    
        // process pair (a,b)
    }
    

You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline() after token-based extraction got you to the end of a line already.

这篇关于逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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