gpt4 book ai didi

c++ - 从 istream 读取自定义坐标类

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:20 25 4
gpt4 key购买 nike

我有一个自定义的 Coordinate 类,想为它重载运算符>>。我不确定执行此操作的正确方法是什么。

坐标的有效流表示是两个逗号分隔的整数,中间允许有空格(例如,“-3 ,4”或“55 , 7”或“1,2”。

到目前为止的代码是:

inline std::istream& operator>> (std::istream& in, Coordinate& c)
{
Coordinate::coord_type x; // int
Coordinate::coord_type y;
in >> x;
// read comma
in >> y;
if (!in.fail())
c = Coordinate(x, y);

return in;
}

你会如何解读分隔符?

最佳答案

让流选择逗号作为您的格式如何:

std::istream& comma(std::istream& in)
{
if ((in >> std::ws).peek() == ',')
in.ignore();
else
in.setstate(std::ios_base::failbit);
return in;
}

然后你可以在你的数据中读取逗号,就像下面这样:

in >> x >> comma >> y;

关于c++ - 从 istream 读取自定义坐标类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23633886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com