新的任意浮点数的重载"cin"
Overload "cin" for a and new arbitrary floating number
我想在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是根据当前问题以这种方式定义的。
派系元素应为double
或float
类型,然后可以使用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) {
// ...
}
};
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- C++中的cin.ignore()函数不适用于整个流
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 如何用对象向量重载 cin(>>)
- C++:在 cin 重载中拼接字符串
- 重载左移和右移运算符(cin和cout)
- 新的任意浮点数的重载"cin"
- "std::cin >> 中"运算符>>"的不明确重载
- 插入>>运算符重载:从 CIN 检索对象的 CTOR 参数时的异常处理
- "std::cin >>"中"运算符>>"的不明确重载
- 操作符重载- cout和cin——ostream函数,不能被引用——它是一个已删除的函数
- 在c++中重载IO操作符时使用cout/cin