问题描述
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 ("text.txt");
推荐答案
首先,创建一个ifstream
:
#include <fstream>
std::ifstream infile("thefile.txt");
两种标准方法是:
-
假设每行包含两个数字,并逐个令牌读取令牌:
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逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!