GeographicLib 2.6
Loading...
Searching...
No Matches
Utility.hpp
Go to the documentation of this file.
1/**
2 * \file Utility.hpp
3 * \brief Header for GeographicLib::Utility class
4 *
5 * Copyright (c) Charles Karney (2011-2024) <karney@alum.mit.edu> and licensed
6 * under the MIT/X11 License. For more information, see
7 * https://geographiclib.sourceforge.io/
8 **********************************************************************/
9
10#if !defined(GEOGRAPHICLIB_UTILITY_HPP)
11#define GEOGRAPHICLIB_UTILITY_HPP 1
12
14#include <iomanip>
15#include <vector>
16#include <sstream>
17#include <cctype>
18#include <ctime>
19#include <cstring>
20
21#if defined(_MSC_VER)
22// Squelch warnings about constant conditional expressions
23# pragma warning (push)
24# pragma warning (disable: 4127)
25#endif
26
27namespace GeographicLib {
28
29 /**
30 * \brief Some utility routines for %GeographicLib
31 *
32 * Example of use:
33 * \include example-Utility.cpp
34 **********************************************************************/
36 private:
37 static bool gregorian(int y, int m, int d) {
38 // The original cut over to the Gregorian calendar in Pope Gregory XIII's
39 // time had 1582-10-04 followed by 1582-10-15. Here we implement the
40 // switch over used by the English-speaking world where 1752-09-02 was
41 // followed by 1752-09-14. We also assume that the year always begins
42 // with January 1, whereas in reality it often was reckoned to begin in
43 // March.
44 return 100 * (100 * y + m) + d >= 17520914; // or 15821015
45 }
46 static bool gregorian(int s) {
47 return s >= 639799; // 1752-09-14
48 }
49 public:
50
51 /**
52 * Convert a date to the day numbering sequentially starting with
53 * 0001-01-01 as day 1.
54 *
55 * @param[in] y the year (must be positive).
56 * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1.
57 * @param[in] d the day of the month (must be positive). Default = 1.
58 * @return the sequential day number.
59 **********************************************************************/
60 static int day(int y, int m = 1, int d = 1);
61
62 /**
63 * Convert a date to the day numbering sequentially starting with
64 * 0001-01-01 as day 1.
65 *
66 * @param[in] y the year (must be positive).
67 * @param[in] m the month, Jan = 1, etc. (must be positive). Default = 1.
68 * @param[in] d the day of the month (must be positive). Default = 1.
69 * @param[in] check whether to check the date.
70 * @exception GeographicErr if the date is invalid and \e check is true.
71 * @return the sequential day number.
72 **********************************************************************/
73 static int day(int y, int m, int d, bool check);
74
75 /**
76 * Given a day (counting from 0001-01-01 as day 1), return the date.
77 *
78 * @param[in] s the sequential day number (must be positive)
79 * @param[out] y the year.
80 * @param[out] m the month, Jan = 1, etc.
81 * @param[out] d the day of the month.
82 **********************************************************************/
83 static void date(int s, int& y, int& m, int& d);
84
85 /**
86 * Given a date as a string in the format yyyy, yyyy-mm, or yyyy-mm-dd,
87 * return the numeric values for the year, month, and day. No checking is
88 * done on these values. The string "now" is interpreted as the present
89 * date (in UTC).
90 *
91 * @param[in] s the date in string format.
92 * @param[out] y the year.
93 * @param[out] m the month, Jan = 1, etc.
94 * @param[out] d the day of the month.
95 * @exception GeographicErr is \e s is malformed.
96 **********************************************************************/
97 static void date(const std::string& s, int& y, int& m, int& d);
98
99 /**
100 * Given the date, return the day of the week.
101 *
102 * @param[in] y the year (must be positive).
103 * @param[in] m the month, Jan = 1, etc. (must be positive).
104 * @param[in] d the day of the month (must be positive).
105 * @return the day of the week with Sunday, Monday--Saturday = 0,
106 * 1--6.
107 **********************************************************************/
108 static int dow(int y, int m, int d) { return dow(day(y, m, d)); }
109
110 /**
111 * Given the sequential day, return the day of the week.
112 *
113 * @param[in] s the sequential day (must be positive).
114 * @return the day of the week with Sunday, Monday--Saturday = 0,
115 * 1--6.
116 **********************************************************************/
117 static int dow(int s) {
118 return (s + 5) % 7; // The 5 offset makes day 1 (0001-01-01) a Saturday.
119 }
120
121 /**
122 * Convert a string representing a date to a fractional year.
123 *
124 * @tparam T the type of the argument.
125 * @param[in] s the string to be converted.
126 * @exception GeographicErr if \e s can't be interpreted as a date.
127 * @return the fractional year.
128 *
129 * The string is first read as an ordinary number (e.g., 2010 or 2012.5);
130 * if this is successful, the value is returned. Otherwise the string
131 * should be of the form yyyy-mm or yyyy-mm-dd and this is converted to a
132 * number with 2010-01-01 giving 2010.0 and 2012-07-03 giving 2012.5. The
133 * string "now" is interpreted as the present date.
134 **********************************************************************/
135 template<typename T> static T fractionalyear(const std::string& s) {
136 try {
137 return val<T>(s);
138 }
139 catch (const std::exception&) {}
140 int y, m, d;
141 date(s, y, m, d);
142 int t = day(y, m, d, true);
143 return T(y) + T(t - day(y)) / T(day(y + 1) - day(y));
144 }
145
146 /**
147 * Convert a object of type T to a string.
148 *
149 * @tparam T the type of the argument.
150 * @param[in] x the value to be converted.
151 * @param[in] p the precision used (default &minus;1).
152 * @exception std::bad_alloc if memory for the string can't be allocated.
153 * @return the string representation.
154 *
155 * If \e p &ge; 0, then the number fixed format is used with \e p bits of
156 * precision. With \e p < 0, there is no manipulation of the format,
157 * except that <code>boolalpha</code> is used to represent bools as "true"
158 * and "false". There is an overload of this function if T is Math::real;
159 * this deals with inf and nan.
160 **********************************************************************/
161 template<typename T> static std::string str(T x, int p = -1) {
162 std::ostringstream s;
163 if (p >= 0) s << std::fixed << std::setprecision(p);
164 s << std::boolalpha << x; return s.str();
165 }
166
167 /**
168 * Trim the white space from the beginning and end of a string.
169 *
170 * @param[in] s the string to be trimmed
171 * @return the trimmed string
172 **********************************************************************/
173 static std::string trim(const std::string& s);
174
175 /**
176 * Lookup up a character in a string.
177 *
178 * @param[in] s the string to be searched.
179 * @param[in] c the character to look for.
180 * @return the index of the first occurrence character in the string or
181 * &minus;1 is the character is not present.
182 *
183 * \e c is converted to upper case before search \e s. Therefore, it is
184 * intended that \e s should not contain any lower case letters.
185 **********************************************************************/
186 static int lookup(const std::string& s, char c);
187
188 /**
189 * Lookup up a character in a char*.
190 *
191 * @param[in] s the char* string to be searched.
192 * @param[in] c the character to look for.
193 * @return the index of the first occurrence character in the string or
194 * &minus;1 is the character is not present.
195 *
196 * \e c is converted to upper case before search \e s. Therefore, it is
197 * intended that \e s should not contain any lower case letters.
198 **********************************************************************/
199 static int lookup(const char* s, char c);
200
201 /**
202 * Convert a string to type T.
203 *
204 * @tparam T the type of the return value.
205 * @param[in] s the string to be converted.
206 * @exception GeographicErr is \e s is not readable as a T.
207 * @return object of type T.
208 *
209 * White space at the beginning and end of \e s is ignored.
210 *
211 * Special handling is provided for some types.
212 *
213 * If T is a floating point type, then inf and nan are recognized.
214 *
215 * If T is bool, then \e s should either be string a representing 0 (false)
216 * or 1 (true) or one of the strings
217 * - "false", "f", "nil", "no", "n", "off", or "" meaning false,
218 * - "true", "t", "yes", "y", or "on" meaning true;
219 * .
220 * case is ignored.
221 *
222 * If T is std::string, then \e s is returned (with the white space at the
223 * beginning and end removed).
224 **********************************************************************/
225 template<typename T> static T val(const std::string& s) {
226 // If T is bool, then the specialization val<bool>() defined below is
227 // used.
228 T x;
229 std::string errmsg, t(trim(s));
230 do { // Executed once (provides the ability to break)
231 std::istringstream is(t);
232 if (!(is >> x)) {
233 errmsg = "Cannot decode " + t;
234 break;
235 }
236 int pos = int(is.tellg()); // Returns -1 at end of string?
237 if (!(pos < 0 || pos == int(t.size()))) {
238 errmsg = "Extra text " + t.substr(pos) + " at end of " + t;
239 break;
240 }
241 return x;
242 } while (false);
243 x = std::numeric_limits<T>::is_integer ? 0 : nummatch<T>(t);
244 if (x == 0)
245 throw GeographicErr(errmsg);
246 return x;
247 }
248
249 /**
250 * Match "nan" and "inf" (and variants thereof) in a string.
251 *
252 * @tparam T the type of the return value (this should be a floating point
253 * type).
254 * @param[in] s the string to be matched.
255 * @return appropriate special value (&plusmn;&infin;, nan) or 0 if none is
256 * found.
257 *
258 * White space is not allowed at the beginning or end of \e s.
259 **********************************************************************/
260 template<typename T> static T nummatch(const std::string& s) {
261 if (s.length() < 3)
262 return 0;
263 std::string t(s);
264 for (std::string::iterator p = t.begin(); p != t.end(); ++p)
265 *p = char(std::toupper(*p));
266 for (size_t i = s.length(); i--;)
267 t[i] = char(std::toupper(s[i]));
268 int sign = t[0] == '-' ? -1 : 1;
269 std::string::size_type p0 = t[0] == '-' || t[0] == '+' ? 1 : 0;
270 std::string::size_type p1 = t.find_last_not_of('0');
271 if (p1 == std::string::npos || p1 + 1 < p0 + 3)
272 return 0;
273 // Strip off sign and trailing 0s
274 t = t.substr(p0, p1 + 1 - p0); // Length at least 3
275 if (t == "NAN" || t == "1.#QNAN" || t == "1.#SNAN" || t == "1.#IND" ||
276 t == "1.#R")
277 return Math::NaN<T>();
278 else if (t == "INF" || t == "1.#INF" || t == "INFINITY")
279 return sign * Math::infinity<T>();
280 return 0;
281 }
282
283 /**
284 * Read a simple fraction, e.g., 3/4, from a string to an object of type T.
285 *
286 * @tparam T the type of the return value.
287 * @param[in] s the string to be converted.
288 * @exception GeographicErr is \e s is not readable as a fraction of type
289 * T.
290 * @return object of type T
291 *
292 * \note The msys shell under Windows converts arguments which look like
293 * pathnames into their Windows equivalents. As a result the argument
294 * "-1/300" gets mangled into something unrecognizable. A workaround is to
295 * use a floating point number in the numerator, i.e., "-1.0/300". (Recent
296 * versions of the msys shell appear \e not to have this problem.)
297 **********************************************************************/
298 template<typename T> static T fract(const std::string& s) {
299 std::string::size_type delim = s.find('/');
300 return
301 !(delim != std::string::npos && delim >= 1 && delim + 2 <= s.size()) ?
302 val<T>(s) :
303 // delim in [1, size() - 2]
304 val<T>(s.substr(0, delim)) / val<T>(s.substr(delim + 1));
305 }
306
307 /**
308 * Read data of type ExtT from a binary stream to an array of type IntT.
309 * The data in the file is in (bigendp ? big : little)-endian format.
310 *
311 * @tparam ExtT the type of the objects in the binary stream (external).
312 * @tparam IntT the type of the objects in the array (internal).
313 * @tparam bigendp true if the external storage format is big-endian.
314 * @param[in] str the input stream containing the data of type ExtT
315 * (external).
316 * @param[out] array the output array of type IntT (internal).
317 * @param[in] num the size of the array.
318 * @exception GeographicErr if the data cannot be read.
319 *
320 * This routine is used to read binary data files for the Geoid,
321 * GravityModel, and MagneticModel classes. In the case of GravityModel
322 * and MagneticMode, the data is published by a government agency as text
323 * files, and the coefficient to realize the models are converted to a
324 * double precision binary format to minimize storage and to simplify
325 * reading the data.
326 *
327 * For GEOGRAPHIC_PRECISION == 2, the data is read faithfully. For
328 * GEOGRAPHICLIB_PRECISION > 2, external data of type double is interpreted
329 * as an approximation of an exact decimal value; this exact number is
330 * convered to a real number at the higher precision.
331 **********************************************************************/
332 template<typename ExtT, typename IntT, bool bigendp>
333 static void readarray(std::istream& str, IntT array[], size_t num) {
334#if GEOGRAPHICLIB_PRECISION < 4
335 if constexpr (sizeof(IntT) == sizeof(ExtT) &&
336 std::numeric_limits<IntT>::is_integer ==
337 std::numeric_limits<ExtT>::is_integer)
338 {
339 // Data is compatible (aside from the issue of endian-ness).
340 str.read(reinterpret_cast<char*>(array), num * sizeof(ExtT));
341 if (!str.good())
342 throw GeographicErr("Failure reading data");
343 if constexpr (bigendp != Math::bigendian) {
344 // endian mismatch -> swap bytes
345 for (size_t i = num; i--;)
346 array[i] = Math::swab<IntT>(array[i]);
347 }
348 }
349 else
350#endif
351 {
352 const int bufsize = 1024; // read this many values at a time
353 ExtT buffer[bufsize]; // temporary buffer
354 int k = int(num); // data values left to read
355 int i = 0; // index into output array
356 while (k) {
357 int n = (std::min)(k, bufsize);
358 str.read(reinterpret_cast<char*>(buffer), n * sizeof(ExtT));
359 if (!str.good())
360 throw GeographicErr("Failure reading data");
361 for (int j = 0; j < n; ++j) {
362 // fix endian-ness
363 ExtT x = bigendp == Math::bigendian ? buffer[j] :
364 Math::swab<ExtT>(buffer[j]);
365#if GEOGRAPHICLIB_PRECISION > 2
366 // typeid doesn't allow if constexpr here
367 if (typeid(ExtT) == typeid(double) &&
368 typeid(IntT) == typeid(Math::real)) {
369 // readarray is used to read in coefficient data rapidly. Thus
370 // 8.3n is stored in its IEEE double representation. This is
371 // fine is the working precision is double. However, when
372 // working at higher precision, how should be interpret the
373 // constant 8.3 appearing in a published table? Possibilities
374 // are
375 //
376 // (a) treat this as an exact decimal number 83/10;
377 //
378 // (b) treat this as the approximate decimal representation of
379 // an exact double precision number 2336242306698445/2^48 =
380 // 8.300000000000000710542735760100185871124267578125
381 //
382 // Here use (a) if the number of significant digits in the
383 // number is 15 or less. Otherwise, we use (b).
384 //
385 // We implement this as follows. Any double which can be
386 // represented as a decimal number with precision 14 = digis10
387 // - 1 (= 15 sig figs) is treated as an approximation to that
388 // decimal number. The high precision number is then obtained
389 // by reading the decimal number at that precision. Otherwise
390 // the double is treated as exact. The high precision number
391 // is obtained by adding zeros in the binary fraction.
392 //
393 // N.B. printing with precision 14 = digis10 - 1 allows short
394 // numbers to be represended with trailing zeros. This isn't
395 // necessarily the case with precision = digits10, e.g., 8.3
396 // becomes 8.300000000000001.
397 //
398 // This prescription doesn't exactly implement the method
399 // proposed. If the published table of numbers includes
400 // 8.300000000000001, this will be interpreted as 8.3. This
401 // doesn't apply to any published magnetic or gravity data.
402 // E.g., the coefficients for EGM96, resp. EGM2008, are given
403 // with precision 11, resp. 14.
404 //
405 // This conversion of doubles to Math::real comes at a
406 // substantial cost. It adds about 14 s to the time it takes
407 // to read the egm2008 gravity model for quad and mpfr
408 // precisions. This is acceptable, however, because high
409 // precision is only used for benchmarking.
410 std::ostringstream str;
411 str << std::scientific
412 << std::setprecision(std::numeric_limits<ExtT>::digits10-1)
413 << x;
414 // Code for GEOGRAPHILIB_PRECISION > 2 and types double/real
415 if (val<ExtT>(str.str()) == x)
416 array[i++] = val<IntT>(str.str());
417 else
418 array[i++] = IntT(x);
419 } else {
420 // Code for GEOGRAPHILIB_PRECISION > 2 but types not
421 // double/real
422 array[i++] = IntT(x);
423 }
424#else
425 // Code for GEOGRAPHILIB_PRECISION <= 2
426 array[i++] = IntT(x);
427#endif
428 }
429 k -= n;
430 }
431 }
432 return;
433 }
434
435 /**
436 * Read data of type ExtT from a binary stream to a vector array of type
437 * IntT. The data in the file is in (bigendp ? big : little)-endian
438 * format.
439 *
440 * @tparam ExtT the type of the objects in the binary stream (external).
441 * @tparam IntT the type of the objects in the array (internal).
442 * @tparam bigendp true if the external storage format is big-endian.
443 * @param[in] str the input stream containing the data of type ExtT
444 * (external).
445 * @param[out] array the output vector of type IntT (internal).
446 * @exception GeographicErr if the data cannot be read.
447 **********************************************************************/
448 template<typename ExtT, typename IntT, bool bigendp>
449 static void readarray(std::istream& str, std::vector<IntT>& array) {
450 if (array.size() > 0)
451 readarray<ExtT, IntT, bigendp>(str, &array[0], array.size());
452 }
453
454 /**
455 * Write data in an array of type IntT as type ExtT to a binary stream.
456 * The data in the file is in (bigendp ? big : little)-endian format.
457 *
458 * @tparam ExtT the type of the objects in the binary stream (external).
459 * @tparam IntT the type of the objects in the array (internal).
460 * @tparam bigendp true if the external storage format is big-endian.
461 * @param[out] str the output stream for the data of type ExtT (external).
462 * @param[in] array the input array of type IntT (internal).
463 * @param[in] num the size of the array.
464 * @exception GeographicErr if the data cannot be written.
465 **********************************************************************/
466 template<typename ExtT, typename IntT, bool bigendp>
467 static void writearray(std::ostream& str, const IntT array[], size_t num)
468 {
469#if GEOGRAPHICLIB_PRECISION < 4
470 if constexpr (sizeof(IntT) == sizeof(ExtT) &&
471 std::numeric_limits<IntT>::is_integer ==
472 std::numeric_limits<ExtT>::is_integer &&
473 bigendp == Math::bigendian)
474 {
475 // Data is compatible (including endian-ness).
476 str.write(reinterpret_cast<const char*>(array), num * sizeof(ExtT));
477 if (!str.good())
478 throw GeographicErr("Failure writing data");
479 }
480 else
481#endif
482 {
483 const int bufsize = 1024; // write this many values at a time
484 ExtT buffer[bufsize]; // temporary buffer
485 int k = int(num); // data values left to write
486 int i = 0; // index into output array
487 while (k) {
488 int n = (std::min)(k, bufsize);
489 for (int j = 0; j < n; ++j)
490 // cast to ExtT and fix endian-ness
491 buffer[j] = bigendp == Math::bigendian ? ExtT(array[i++]) :
492 Math::swab<ExtT>(ExtT(array[i++]));
493 str.write(reinterpret_cast<const char*>(buffer), n * sizeof(ExtT));
494 if (!str.good())
495 throw GeographicErr("Failure writing data");
496 k -= n;
497 }
498 }
499 return;
500 }
501
502 /**
503 * Write data in an array of type IntT as type ExtT to a binary stream.
504 * The data in the file is in (bigendp ? big : little)-endian format.
505 *
506 * @tparam ExtT the type of the objects in the binary stream (external).
507 * @tparam IntT the type of the objects in the array (internal).
508 * @tparam bigendp true if the external storage format is big-endian.
509 * @param[out] str the output stream for the data of type ExtT (external).
510 * @param[in] array the input vector of type IntT (internal).
511 * @exception GeographicErr if the data cannot be written.
512 **********************************************************************/
513 template<typename ExtT, typename IntT, bool bigendp>
514 static void writearray(std::ostream& str, std::vector<IntT>& array) {
515 if (array.size() > 0)
516 writearray<ExtT, IntT, bigendp>(str, &array[0], array.size());
517 }
518
519 /**
520 * Parse a KEY [=] VALUE line.
521 *
522 * @param[in] line the input line.
523 * @param[out] key the KEY.
524 * @param[out] value the VALUE.
525 * @param[in] equals character representing "equals" to separate KEY and
526 * VALUE, if NULL (the default) use first space character.
527 * @param[in] comment character to use as the comment character; if
528 * non-NULL, this character and everything after it is discarded; default
529 * is '#'.
530 * @exception std::bad_alloc if memory for the internal strings can't be
531 * allocated.
532 * @return whether a key was found.
533 *
534 * The \e comment character (default is '#') and everything after it are
535 * discarded and the result trimmed of leading and trailing white space.
536 * Use the \e equals delimiter character (or, if it is NULL -- the default,
537 * the first white space) to separate \e key and \e value. \e key and \e
538 * value are trimmed of leading and trailing white space. If \e key is
539 * empty, then \e value is set to "" and false is returned.
540 **********************************************************************/
541 static bool ParseLine(const std::string& line,
542 std::string& key, std::string& value,
543 char equals = '\0', char comment = '#');
544
545 /**
546 * Set the binary precision of a real number.
547 *
548 * @param[in] ndigits the number of bits of precision. If ndigits is 0
549 * (the default), then determine the precision from the environment
550 * variable GEOGRAPHICLIB_DIGITS. If this is undefined, use ndigits =
551 * 256 (i.e., about 77 decimal digits).
552 * @return the resulting number of bits of precision.
553 *
554 * This only has an effect when GEOGRAPHICLIB_PRECISION >= 5. The
555 * precision should only be set once and before calls to any other
556 * GeographicLib functions. (Several functions, for example Math::pi(),
557 * cache the return value in a static local variable. The precision needs
558 * to be set before a call to any such functions.) In multi-threaded
559 * applications, it is necessary also to set the precision in each thread
560 * (see the example GeoidToGTX.cpp). If GEOGRAPHICLIB_PRECISION > 5, then
561 * the precision is set to GEOGRAPHICLIB_PRECISION, the compile-time value,
562 * and \e ndigits is ignored.
563 *
564 * \note Use Math::digits() to return the current precision in bits.
565 **********************************************************************/
566 static int set_digits(int ndigits = 0);
567
568 };
569
570 /**
571 * The specialization of Utility::val<T>() for strings.
572 *
573 * @param[in] s the string to be converted.
574 * @exception GeographicErr is \e s is not readable as a T.
575 * @return the string trimmed of its whitespace.
576 **********************************************************************/
577 template<> inline std::string Utility::val<std::string>(const std::string& s)
578 { return trim(s); }
579
580 /**
581 * The specialization of Utility::val<T>() for bools.
582 *
583 * @param[in] s the string to be converted.
584 * @exception GeographicErr is \e s is not readable as a T.
585 * @return boolean value.
586 *
587 * \e s should either be string a representing 0 (false)
588 * or 1 (true) or one of the strings
589 * - "false", "f", "nil", "no", "n", "off", or "" meaning false,
590 * - "true", "t", "yes", "y", or "on" meaning true;
591 * .
592 * case is ignored.
593 **********************************************************************/
594 template<> inline bool Utility::val<bool>(const std::string& s) {
595 std::string t(trim(s));
596 if (t.empty()) return false;
597 bool x;
598 {
599 std::istringstream is(t);
600 if (is >> x) {
601 int pos = int(is.tellg()); // Returns -1 at end of string?
602 if (!(pos < 0 || pos == int(t.size())))
603 throw GeographicErr("Extra text " + t.substr(pos) +
604 " at end of " + t);
605 return x;
606 }
607 }
608 for (std::string::iterator p = t.begin(); p != t.end(); ++p)
609 *p = char(std::tolower(*p));
610 switch (t[0]) { // already checked that t isn't empty
611 case 'f':
612 if (t == "f" || t == "false") return false;
613 break;
614 case 'n':
615 if (t == "n" || t == "nil" || t == "no") return false;
616 break;
617 case 'o':
618 if (t == "off") return false;
619 else if (t == "on") return true;
620 break;
621 case 't':
622 if (t == "t" || t == "true") return true;
623 break;
624 case 'y':
625 if (t == "y" || t == "yes") return true;
626 break;
627 default:
628 break;
629 }
630 throw GeographicErr("Cannot decode " + t + " as a bool");
631 }
632
633 /**
634 * Convert a Math::real object to a string.
635 *
636 * @param[in] x the value to be converted.
637 * @param[in] p the precision used (default &minus;1).
638 * @exception std::bad_alloc if memory for the string can't be allocated.
639 * @return the string representation.
640 *
641 * If \e p &ge; 0, then the number fixed format is used with p bits of
642 * precision. With p < 0, there is no manipulation of the format. This is
643 * an overload of str<T> which deals with inf and nan.
644 **********************************************************************/
645 template<> inline std::string Utility::str<Math::real>(Math::real x, int p) {
646 using std::isfinite;
647 if (!isfinite(x))
648 return x < 0 ? std::string("-inf") :
649 (x > 0 ? std::string("inf") : std::string("nan"));
650 std::ostringstream s;
651 if (p >= 0) s << std::fixed << std::setprecision(p);
652 s << x; return s.str();
653 }
654
655} // namespace GeographicLib
656
657#if defined(_MSC_VER)
658# pragma warning (pop)
659#endif
660
661#endif // GEOGRAPHICLIB_UTILITY_HPP
Header for GeographicLib::Constants class.
#define GEOGRAPHICLIB_EXPORT
Definition Constants.hpp:59
Exception handling for GeographicLib.
static T infinity()
Definition Math.cpp:308
static const bool bigendian
Definition Math.hpp:181
static T NaN()
Definition Math.cpp:301
static T swab(T x)
Definition Math.hpp:547
Some utility routines for GeographicLib.
Definition Utility.hpp:35
static void readarray(std::istream &str, std::vector< IntT > &array)
Definition Utility.hpp:449
static void writearray(std::ostream &str, std::vector< IntT > &array)
Definition Utility.hpp:514
static T fractionalyear(const std::string &s)
Definition Utility.hpp:135
static void date(int s, int &y, int &m, int &d)
Definition Utility.cpp:89
static void readarray(std::istream &str, IntT array[], size_t num)
Definition Utility.hpp:333
static void writearray(std::ostream &str, const IntT array[], size_t num)
Definition Utility.hpp:467
static int dow(int y, int m, int d)
Definition Utility.hpp:108
static int dow(int s)
Definition Utility.hpp:117
static T fract(const std::string &s)
Definition Utility.hpp:298
static T val(const std::string &s)
Definition Utility.hpp:225
static T nummatch(const std::string &s)
Definition Utility.hpp:260
static std::string trim(const std::string &s)
Definition Utility.cpp:149
static int day(int y, int m=1, int d=1)
Definition Utility.cpp:22
static std::string str(T x, int p=-1)
Definition Utility.hpp:161
Namespace for GeographicLib.