为什么 i(f)流无法读取双精度

Why i(f)stream can't read a double

本文关键字:读取 双精度 为什么      更新时间:2023-10-16

我正在编写一个程序,需要实现的一件事是过载>>操作员一次以一次读取点。我尝试了什么:

std::istream& operator >>(std::istream& is, const Point& point)
{
  double temp;
  is >> temp;
  point.setx(temp);
  is.ignore(3,';');
  is >> temp;
  point.sety(temp);
  is.ignore(3,';');
}

它某种程度上未能在VS2019中编译(如果很重要的话(,并说没有操作员>>接受std::istream&double作为参数。任何类型的temp仍然存在问题。它是intchar*,不取决于我是从istream还是从ifstream阅读。

这种行为的原因是什么?

也许您忘记了#include <iostream>?没有这些,您希望像您所引用的那样收到一条错误消息。

解决此问题后,我希望看到其他几个警告/错误。首先,即使operator>>似乎正在修改已通过的Point(这是预期的(,您也可以通过point通过CC_11。您可能要删除const

第二,您已声明您的operator>>返回std::istream &,但未能返回任何内容。您可能想在结束之前添加return is;

此代码编译:

#include <iostream>
struct Point { 
    double x;
    double y;
    void setx(double x_) { x = x_; }
    void sety(double y_) { y = y_; }
};
std::istream& operator >>(std::istream& is, Point& point)
{
  double temp;
  is >> temp;
  point.setx(temp);
  is.ignore(3,';');
  is >> temp;
  point.sety(temp);
  is.ignore(3,';');
  return is;
}