在 C++ 中使用 ifstream 逐行读取文件 [英] Read file line by line using ifstream in C++

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

问题描述

file.txt 的内容为:

The contents of file.txt are:

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

其中 5 3 是坐标对.如何在 C++ 中逐行处理此数据?

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?

ifstream myfile;
myfile.open ("file.txt");

推荐答案

首先,制作一个ifstream:

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

两种标准方法是:

  1. 假设每一行由两个数字组成并逐个标记读取:

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

  • 基于行的解析,使用字符串流:

  • 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)
    }
    

  • 您不应该混合 (1) 和 (2),因为基于令牌的解析不会吞噬换行符,因此如果您使用 getline() 在基于令牌的提取已经让你到达一行的末尾之后.

    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.

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

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