fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <stdexcept>
  5.  
  6. int gcd(int a, int b)
  7. {
  8. a = std::abs(a);
  9. b = std::abs(b);
  10.  
  11. while (a)
  12. {
  13. int temp = a;
  14. a = b % a;
  15. b = temp;
  16. }
  17.  
  18. return b;
  19. }
  20.  
  21. struct Rational
  22. {
  23. Rational(std::string);
  24. friend std::ostream& operator<<(std::ostream&, const Rational&);
  25.  
  26. private:
  27. void reduce();
  28.  
  29. std::string equation;
  30. int numerator;
  31. int denominator;
  32. };
  33.  
  34. void Rational::reduce()
  35. {
  36. int divisor = gcd(numerator, denominator);
  37. numerator /= divisor;
  38. denominator /= divisor;
  39. }
  40.  
  41. Rational::Rational(std::string inputString) : equation(inputString)
  42. {
  43. std::istringstream in(inputString);
  44.  
  45. char dummy;
  46. if (!(in >> numerator) || !(in >> dummy) || !(in >> denominator))
  47. throw std::invalid_argument("ERROR: Invalid argument - \"" + inputString + '"');
  48.  
  49. if (denominator == 0)
  50. throw std::domain_error("ERROR: Denominator cannot be 0 - \"" + inputString + '"');
  51.  
  52. reduce();
  53. }
  54.  
  55. std::ostream& operator<<(std::ostream& os, const Rational& r)
  56. {
  57. os << r.numerator;
  58.  
  59. if (r.denominator != 1)
  60. os << " / " << r.denominator;
  61.  
  62. return os;
  63. }
  64.  
  65. int main()
  66. {
  67. std::string line;
  68. while (std::getline(std::cin, line) && line.size())
  69. {
  70. try {
  71. std::cout << Rational(line) << '\n';
  72. }
  73.  
  74. catch (std::exception& ex)
  75. {
  76. std::cout << ex.what() << '\n';
  77. }
  78.  
  79. std::cout << '\n';
  80. }
  81. }
Success #stdin #stdout 0s 3484KB
stdin
9/3
8/10
abcd
100/0
stdout
3

4 / 5

ERROR: Invalid argument - "abcd"

ERROR: Denominator cannot be 0 - "100/0"