C++输入运算符过载">>"

C++ input operator overload ">>"

本文关键字:gt 输入 运算符 C++      更新时间:2023-10-16

我有一个有理数类,它由两个整数组成:主格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"这一事实开始,那么进行转换通常会非常简单——特别是,简单到我认为几乎任何人都可以浏览代码,并找出每一部分应该做什么。


  1. 老实说,我并不想让人讨厌,但如果我在维护代码,并遇到你的operator>>,我会有两种可能的反应之一:如果它显然有错误,请立即替换它。否则,请将其列入"技术债务"清单,并尽快更换。简单的事实是,就目前的情况来看,甚至需要进行大量的研究才能确定应该支持哪些输入格式,更不用说代码的哪一部分处理每一种格式,或者整个过程应该如何协同工作以产生有意义的结果

注释中提到的问题(p没有出现在c=is.peek()语句中)源于p实际上存储在ws中(它存储在is >> ws中)。

上面的代码也没有提到ws,但我认为它是char