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");
两种标准方法是:
假设每一行由两个数字组成,逐个读取:
int a, b; while (infile >> a >> b) { // process pair (a,b) }
基于行的解析,使用字符串流:
#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/