新的任意浮点数的重载"cin"

Overload "cin" for a and new arbitrary floating number

本文关键字:重载 cin 浮点数 任意      更新时间:2023-10-16

我想在c++中重载输入运算符,这样我就可以在新类型中正确地替换输入,我有以下

struct{
           uint64_t frac;
           unit64_t exp;
  };

我想要在frac中浮点之后和exp.中浮点之前出现的内容

请帮忙!

试着做一些类似的事情

struct Number               //Changed this because I don't know what you are looking for
{
    int frac;
    double exp;
};

istream& operator>>(istream& in, Number& number)
{
    double temp;
    in >> temp;
    number.frac = (int)temp;             //You need to calculate frac here not sure what you are looking for
    number.exp = temp - number.frac;     //Same for exp
    return in;
}

您可以使用字符串输入数字,然后通过重载<<运算符来填充struct元素:

#include <iostream>
#include <string>
 struct Frac {
           unsigned long  frac; //uint64_t
           unsigned long exp;  //uint64_t
   friend std::istream& operator >>(std::istream& is, Frac &f)
   {
      std::string s;
      is >> s;
      std::size_t n = s.find(".");
      if (n != std::string::npos)
      {
         f.frac = std::atoll(s.substr(0,n).c_str());
         f.exp = std::atoll(s.substr(n+1).c_str());
      }
      else
      {
         f.frac = std::atoll(s.c_str());
         f.exp  = 0 ;
      }
   }
};
int main()
{
  Frac f;
  std::cin>>f;
  std::cout << f.frac <<" "<< f.exp;
}

请参阅此处

编辑:

对于1.23、1.230和1.023等输入,以上将给出相同的结果因为CCD_ 3是根据当前问题以这种方式定义的。

派系元素应为doublefloat类型,然后可以使用std::atof

template <class Elem, class Tr>
std::basic_istream<Elem, Tr>& operator>>(std::basic_istream<Elem, Tr>& str,
    Number num) {
    char ch;
    return str >> num.exp >> ch >> num.frac;
}

然而,这是一种有点特殊的输入格式。通常小数点左边的数字是分数的一部分,这些数字的数量用于调整指数。

假设您不知道用户定义类型的流输入是如何实现的,并且您要求提供这些信息,而不是要求某人只为您编写一个自定义输入函数:

要为自己的类型重载输入操作,只需在定义类型的同一命名空间中为非成员operator>>提供兼容的签名。

struct S {int i}; // type to read from input stream
std::istream &operator >> (std::istream &is, S &s) {
  // read from stream
  int i;
  is >> i;
  // check for errors, validate stream input, etc.
  // ...
  // return the input stream
  return i;
}
int main() {
    S s;
    std::cin >> s;
}

operator >>通常需要访问该类型的私有成员。您可以将操作员声明为朋友。事实上,您可以同时定义非成员operator >>,它将被放入正确的命名空间:

class C {
  int i;
  friend std::istream &operator >> (std::istream &is, S &s) {
    // ...
  }
};