PSCF v1.1
Rational.cpp
1/*
2* Util Package - C++ Utilities for Scientific Computation
3*
4* Copyright 2010 - 2017, The Regents of the University of Minnesota
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "Rational.h"
9
10namespace Util
11{
12
13 /*
14 * Output stream inserter for a Rational.
15 */
16 std::ostream& operator << (std::ostream& out, Rational const &a)
17 {
18 UTIL_CHECK(a.den_ > 0);
19 out << a.num_;
20 if (a.den_ != 1) {
21 out << "/" << a.den_ ;
22 }
23 return out;
24 }
25
26 #ifdef UTIL_CXX11
27 /*
28 * Input stream extractor for a Rational.
29 */
30 std::istream& operator >> (std::istream& in, Rational &a)
31 {
32 std::string word;
33 in >> word;
34 int size = word.size();
35
36 // Search for '/' character in word
37 std::size_t slashId = word.find('/');
38 bool hasSlash = false;
39 if (slashId != std::string::npos) {
40 hasSlash = true;
41 }
42
43 // Extract numerator and denominator
44 if (hasSlash) {
45 UTIL_CHECK(slashId > 0);
46 UTIL_CHECK((int)slashId < size - 1);
47 int numSize = slashId;
48 int denSize = size - slashId - 1;
49 std::string numStr = word.substr(0, numSize);
50 std::string denStr = word.substr(slashId + 1, denSize);
51 a.num_ = std::stoi(numStr);
52 a.den_ = std::stoi(denStr);
53 } else {
54 a.num_ = std::stoi(word);
55 a.den_ = 1;
56 }
57 UTIL_CHECK(a.den_ > 0);
58
59 return in;
60 }
61 #endif
62
63}
A Rational number (a ratio of integers).
Definition: Rational.h:34
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition: global.h:68
Utility classes for scientific computation.
Definition: accumulators.mod:1
std::istream & operator>>(std::istream &in, Pair< Data > &pair)
Input a Pair from an istream.
Definition: Pair.h:44
std::ostream & operator<<(std::ostream &out, const Pair< Data > &pair)
Output a Pair to an ostream, without line breaks.
Definition: Pair.h:57