使用C ++中的ifstream逐行读取文件file.txt的内容是:5 36 47 110 511 612 312 45 3坐标对在哪里。如何在C ++中逐行处理此数据?我能够得到第一行,但是如何获得文件的下一行?ifstream myfile;myfile.open ("text.txt");
4 回答
ABOUTYOU
TA贡献1812条经验 获得超5个赞
由于你的坐标是成对的,为什么不为它们写一个结构?
struct CoordinatePair{
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}- 4 回答
- 0 关注
- 4126 浏览
添加回答
举报
0/150
提交
取消
