Here, the denominator is read only if the first number is followed by the character ’/’; otherwise,
a denominator of 1 is assumed, and the integer read is interpreted as the whole fraction. Hence, the
denominator is optional.
This implementation also tests whether a denominator with value 0 was read. In this case, the
ios_base::failbit is set, which might trigger a corresponding exception (see Section 15.4.4,
page 762). Of course, the behavior can be implemented differently if the denominator is zero. For
example, an exception could be thrown directly, or the check could be skipped so that the fraction is
initialized with zero, which would throw the appropriate exception by class Fraction.
Finally, the state of the stream is checked, and the new value is assigned to the fraction only if no
input error occurred. This final check should always be done to make sure that the value of an object
is changed only if the read was successful.
Of course, it can be argued whether it is reasonable to read integers as fractions. In addition,
there are other subtleties that may be improved. For example, the numerator must be followed by
the character ’/’ without separating whitespaces. But the denominator may be preceded by arbitrary
whitespaces because normally, these are skipped. This hints at the complexity involved in reading
nontrivial data structures.
Here, the denominator is read only if the first number is followed by the character ’/’; otherwise,
a denominator of 1 is assumed, and the integer read is interpreted as the whole fraction. Hence, the
denominator is optional.
This implementation also tests whether a denominator with value 0 was read. In this case, the
ios_base::failbit is set, which might trigger a corresponding exception (see Section 15.4.4,
page 762). Of course, the behavior can be implemented differently if the denominator is zero. For
example, an exception could be thrown directly, or the check could be skipped so that the fraction is
initialized with zero, which would throw the appropriate exception by class Fraction.
Finally, the state of the stream is checked, and the new value is assigned to the fraction only if no
input error occurred. This final check should always be done to make sure that the value of an object
is changed only if the read was successful.
Of course, it can be argued whether it is reasonable to read integers as fractions. In addition,
there are other subtleties that may be improved. For example, the numerator must be followed by
the character ’/’ without separating whitespaces. But the denominator may be preceded by arbitrary
whitespaces because normally, these are skipped. This hints at the complexity involved in reading
nontrivial data structures.
การแปล กรุณารอสักครู่..
![](//thimg.ilovetranslation.com/pic/loading_3.gif?v=b9814dd30c1d7c59_8619)