我的文件内容是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");
既然你的坐标属于成对的,为什么不为他们写一个结构呢?
struct CoordinatePai
{
int x;
int y;
};
然后你可以为istreams写一个重载的提取操作符:
std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
is >> coordinates.x >> coordinates.y;
return is;
}
然后你可以直接读取一个坐标文件,像这样的矢量:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
char filename[] = "coordinates.txt";
std::vector<CoordinatePair> v;
std::ifstream ifs(filename);
if (ifs) {
std::copy(std::istream_iterator<CoordinatePair>(ifs),
std::istream_iterator<CoordinatePair>(),
std::back_inserter(v));
}
else {
std::cerr << "Couldn't open " << filename << " for reading\n";
}
// Now you can work with the contents of v
}
首先,你做一个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; } // erro
// process pair (a,b)
}
你不应该混淆(1)和(2),因为基于标记的解析不会吞噬换行符,所以如果getline()在基于标记的提取之后使用,最后可能会出现虚假的空行。