S
Saeed Amrollahi
Hi
I am going to design and implement a typical library for rational
numbers, something like
Boost.Rational. My class is actually implemented as a template, in a
similar manner to the standard complex class.
I want to handle Whole numbers like rational numbers; As you know,
from point of math view
whole numbers are subset of rational numbers, for example 3 is 3/1.
I like to read both kind of numbers (whole and fraction) in a single
operator>> function. I mean
I want to handle
a
a/b
together. I finally ended with an assumption: Immediately, after
numerator, I should get '/':
template<class T>
std::istream& operator>>(std::istream& is, rational<T>& r)
{
/*
handle the following foramts:
n/d
n
*/
T n, d;
char c = 0; // for '/'
is >> n;
if (is.good()) {
is.get(c);
}
if (c == '/') { // fraction
if (is.good())
is >> d;
}
else if (std::isspace(c) || is.rdstate() & std::ios_base::eofbit)
{ // whole number
d = 1;
}
else {
is.clear(std::ios_base::badbit); // set state
}
if (is) // everything is good
r = rational<T>(n, d);
return is;
}
I know, my code may be inefficient.
Any suggestion for better/more elegant handling different formats and
better efficiency?
Thanks in advance,
-- Saeed Amrollahi
I am going to design and implement a typical library for rational
numbers, something like
Boost.Rational. My class is actually implemented as a template, in a
similar manner to the standard complex class.
I want to handle Whole numbers like rational numbers; As you know,
from point of math view
whole numbers are subset of rational numbers, for example 3 is 3/1.
I like to read both kind of numbers (whole and fraction) in a single
operator>> function. I mean
I want to handle
a
a/b
together. I finally ended with an assumption: Immediately, after
numerator, I should get '/':
template<class T>
std::istream& operator>>(std::istream& is, rational<T>& r)
{
/*
handle the following foramts:
n/d
n
*/
T n, d;
char c = 0; // for '/'
is >> n;
if (is.good()) {
is.get(c);
}
if (c == '/') { // fraction
if (is.good())
is >> d;
}
else if (std::isspace(c) || is.rdstate() & std::ios_base::eofbit)
{ // whole number
d = 1;
}
else {
is.clear(std::ios_base::badbit); // set state
}
if (is) // everything is good
r = rational<T>(n, d);
return is;
}
I know, my code may be inefficient.
Any suggestion for better/more elegant handling different formats and
better efficiency?
Thanks in advance,
-- Saeed Amrollahi