[英]Read points from a stream that is only one line
我有一个文件,它首先告诉我我将在下一行阅读多少点。 因此,例如我的文件如下所示:
7
a,b c,d e,f g,h, i,j k,l m,n
所以我知道 7 之后的下一行是 7 对整数,用逗号分隔,每对用空格分隔。
我想要的是:拥有 7 个 Point 元素的向量。
我有一个名为 Point 的类:
class Point {
public:
int x;
int y;
bool operator==(const Point q){
return (q.x == this->x && q.y == this->y);
}
};
因此,当我阅读此文件时,我想要一个向量 V,其中:
V[0].x = a
V[0].y = b
V[1].x = c
V[1].y = d
等等。
我可以很好地读取 7,但是如何分别读取 7 对整数中的每一对? 我需要这个,因为我要将 (a,b) (c,d)... 存储在一个向量中。
不仅是2分。 文件的第一行告诉我要存储多少点。
它们不是从标准输入中读取的。
它们是从文件中读取的。
我尝试使用 sscanf 但我认为这仅适用于您有多行包含此信息并且我不想修改我的格式。
这是我到目前为止:
void process_file(string filename){
ifstream thracklefile;
string line;
int set_size;
thracklefile.open(filename);
getline(thracklefile,line); //store set size.
set_size = stoi(line);
//Store points in following line
points.clear();
points.resize(set_size);
getline(thracklefile,line); //store the points.
}
我不想忽略逗号,每个逗号都是我想为每个 Point 存储的信息的一部分。
我认为评论中的大部分讨论都是关于语义的。 建议您“忽略”逗号,但您不能这样做,因为它们在文件中。 也许更好的术语是“丢弃”。 使用“忽略”一词是因为有一个 C++ iostream 函数ignore
。
有很多方法可以处理这个问题。 一种选择是覆盖流插入/提取运算符:
class Point {
public:
int x;
int y;
// Don't really need this as members are public, but
// in case you change that in the future....
friend istream& operator>>(istream& in, Point& p);
friend ostream& operator<<(ostream& out, const Point& p);
};
istream& operator>>(istream& in, Point& p)
{
char separator;
// Try to read <int><char><int>
in >> p.x >> separator >> p.y;
// The stream may be in an error state here. That
// is ok. Let the caller handle that
// Also note that we discard (ignore) "separator"
return in;
}
ostream& operator<<(ostream& out, const Point& p)
{
out << p.x << ',' << p.y;
return out;
}
int main() {
int num_points;
std::cin >> num_points;
Point p;
for (int i = 0; i < num_points; i++) {
if (!(std::cin >> p)) {
// There was an error
std::cout << "File format error!" << std::endl;
break;
}
std::cout << p << std::endl;
}
return 0;
}
该示例使用cin
但任何流都应该可以工作,包括ifstream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.