#include #include #include #include "rational7.h" using namespace std; // Input (extraction) operator for rational class // This code uses conditional statement: // (bool-expression) ? expr_when_true : expr_when_false ; istream& operator>> (istream& ins, rational& r) { string s; bool isSlash = false, isNegative = false; bool isWhole = false; // Read a string (can read char by char, but less efficient). ins >> s; bool isValid = true; // Look at every character to see if it is valid for (int i = 0; i < s.length() && isValid; i++) { if (s[i] == '-') { // Must be at the beginning only isValid = ( i == 0) ? true : false; isNegative = (isValid) ? true : false; } else if (s[i] == '/') { // Must not be at the beginning or end or duplicated. isValid = (i == 0 || i == s.length()-1 || (i == 1 && isNegative ) || isSlash) ? false : true; isSlash = true; } else if (!isdigit(s[i])) { // Only valid characters are '-', '/' // and digits. isValid = false; } } // Set the failbit when not valid. if (isValid != true) { ins.setstate(ios::failbit); cerr << "Invalid rational" << endl; return ins; } // Smarter to use temporary variables because there can still be // an error with the denominator. We don't want to change the // rational if the read was unsucessful. int n, d; char c; istringstream str(s); if (isSlash) { str >> n >> c >> d; } else { str >> n; d = 1; } if (d == 0) { ins.setstate(ios::failbit); cerr << "Invalid rational" << endl; return ins; } r.set(n, d); return ins; } int main() { rational r1; cin >> r1; }