c++ - 在 C++ 中使用 ifstream 逐行读取文件

标签 c++ file-io ofstream

file.txt的内容是:

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

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

我可以获取文件的第一行,但是如何获取文件的下一行?

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

最佳答案

首先,制作一个ifstream:

#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; } // error
    
        // process pair (a,b)
    }
    

你不应该混合 (1) 和 (2),因为基于标记的解析不会吞噬换行符,所以如果你使用 getline() 在基于标记的提取之后,您已经到了一行的末尾。

关于c++ - 在 C++ 中使用 ifstream 逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38620067/

相关文章:

c++ - 程序崩溃时 C++ ofstream 的行为

c++ - 使用两个标准对结构数组进行排序 C++

c++ - for 循环中没有检查条件,但循环仍然终止 C++

java - 将 'getSelectedFile' 写成字符串 (Java)

c# - 为什么我的流不可读?

C++ boost asio Windows 文件句柄 a​​sync_read_until 无限循环 - 没有 eof

c++ - 对于 ifstream 的每一行,ofstream 到一个文件。垃圾保存在他们身上?

c++ - 如何使用 C++ 将 MXNET 自定义运算符构建到单独的库/包中?

c++ - STL 或 Boost 能否帮助按值对 map 进行排序?

c++ - 在 C++ 中将数组写入文本文件