C++输入运算符过载">>"
C++ input operator overload ">>"
我有一个有理数类,它由两个整数组成:主格num
和分母den
。
下面的运算符应该从流中读取有理数。
istream& operator >> (istream& Is, rational& r) {
char c; //Test char.
double n; //Could be either the numerator of the fraction or the antiperiod of the repeating decimal number.
Is >> n;
int i = 0;
for (; n*10-pow(10, i+1) < 1 && int(n) != 0; i++) {
n *= 10;
}
for (; int(n*10) % 10; i++) {
n *= 10;
}
n /= pow(10, i);
if (i == 0) {
r.num = n;
Is >> ws;
c = Is.peek();
if (c == '/') {
c = Is.get();
Is >> r.den;
} else {
r.den = 1;
}
r.normalize(); //This function normalizes the fraction.
} else {
Is >> ws;
c = Is.peek();
if (c == 'p' || c == 'P') {
int p; //Period of the repeating decimal number.
c = Is.get();
Is >> p;
vector<int> a = genFrac(n, p); //This function returns the fraction which express the decimal repeating number. It returns a "vector<int>" with the nominator at index 1 e denominator at index 0.
r.num = a[1];
r.den = a[0];
} else {
i = 0;
for (; n*10-pow(10, i+1) < 1 && int(n) != 0; i++) {
n *= 10;
}
for (; int(n*10) % 10 != 0; i++) {
n *= 10;
}
int pot10 = pow(10, i);
r.num = n;
r.den = pot10;
}
r.normalize();
}
return Is;
}
我写这段代码是为了实现我的"rational"类的输入。我从C++书中写的那个修改了它,以便可以输入十进制数字,包括重复的数字。
它应该能够处理以下类型的输入:
- 9/8
- 9
- 9.87
- 1.p3
但它不起作用,甚至我从书中复制的部分也不起作用。
有人能帮我吗?
我想我会写得有点不同1。
除非你真的需要做其他事情,否则我会从读取整个输入"块"开始(即,直到下一个空格的所有字符),然后找出它应该如何表示一个数字,并为每个可能的表示调用一个单独的函数:
std::istream &operator>>(std::istream &is, rational &r) {
std::string temp;
Is >> temp;
if (temp.find('/') != std::string::npos)
r = cvt_fraction(temp, Is);
else if (temp.find_first_of("pP") != std::string::npos)
r = cvt_repeating(temp, Is);
else if (temp.find('.') != std::string::npos)
r = cvt_float(temp, Is);
else
r = cvt_int(temp, Is);
return Is;
}
我将istream传递给每个流有两个原因:首先,如果他们在输入中发现垃圾,他们可以设置流的失败位。其次,如果他们真的需要阅读更多的输入,他们可以(但如果真的需要的话,我会有点惊讶)。
在我看来,这些转换函数中的每一个都应该是相当琐碎的:如果我从字符串应该是digits "/" digits
或"digits"p"digitals"这一事实开始,那么进行转换通常会非常简单——特别是,简单到我认为几乎任何人都可以浏览代码,并找出每一部分应该做什么。
- 老实说,我并不想让人讨厌,但如果我在维护代码,并遇到你的
operator>>
,我会有两种可能的反应之一:如果它显然有错误,请立即替换它。否则,请将其列入"技术债务"清单,并尽快更换。简单的事实是,就目前的情况来看,甚至需要进行大量的研究才能确定应该支持哪些输入格式,更不用说代码的哪一部分处理每一种格式,或者整个过程应该如何协同工作以产生有意义的结果
注释中提到的问题(p
没有出现在c=is.peek()
语句中)源于p
实际上存储在ws
中(它存储在is >> ws
中)。
上面的代码也没有提到ws
,但我认为它是char
。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type