string_conv.h
Go to the documentation of this file.
1 /*
2  -------------------------------------------------------------------
3 
4  Copyright (C) 2006-2020, Andrew W. Steiner
5 
6  This file is part of O2scl.
7 
8  O2scl is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 3 of the License, or
11  (at your option) any later version.
12 
13  O2scl is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17 
18  You should have received a copy of the GNU General Public License
19  along with O2scl. If not, see <http://www.gnu.org/licenses/>.
20 
21  -------------------------------------------------------------------
22 */
23 #ifndef O2SCL_STRING_CONV_H
24 #define O2SCL_STRING_CONV_H
25 /** \file string_conv.h
26  \brief Various string conversion functions
27 */
28 
29 #include <iostream>
30 #include <cmath>
31 #include <string>
32 #include <vector>
33 #include <fstream>
34 #include <sstream>
35 
36 // For numeric_limits for dtos()
37 #include <limits>
38 
39 // For screenify()
40 #include <o2scl/misc.h>
41 
42 #ifndef DOXYGEN_NO_O2NS
43 namespace o2scl {
44 #endif
45 
46  /// \name Functions in src/base/string_conv.h
47  //@{
48  /** \brief Convert a pointer to a string
49 
50  This uses an \c ostringstream to convert a pointer to a string
51  and is architecture-dependent.
52  */
53  std::string ptos(void *p);
54 
55  /** \brief Convert an integer to a string
56  */
57  std::string itos(int x);
58 
59  /** \brief Convert a size_t to a string
60  */
61  std::string szttos(size_t x);
62 
63  /** \brief Convert a boolean value to a string
64 
65  This returns \c "1" for true and \c "0" for false.
66  */
67  std::string btos(bool b);
68 
69  /** \brief Convert a double to a string
70 
71  If \c auto_prec is false, then the number is converted to
72  a string in the <tt>ios::scientific</tt> mode, otherwise,
73  neither the scientific or fixed mode flags are set and the
74  number is converted to a string in "automatic" mode.
75  */
76  template<class fp_t>
77  std::string dtos(const fp_t &x, int prec=6, bool auto_prec=false) {
78 
79  std::ostringstream strout;
80 
81  size_t max=std::numeric_limits<fp_t>::digits10;
82  if (prec<0 || (prec>((int)max) && prec>6)) prec=((int)max);
83 
84  if (prec!=0) {
85  if (!auto_prec) strout.setf(std::ios::scientific);
86  strout.precision(prec);
87  }
88 
89  if (strout << x) {
90  return strout.str();
91  }
92 
93  O2SCL_ERR2("Conversion from floating point value to string failed in ",
94  "dtos(fp_t,int,bool).",exc_einval);
95  return "";
96  }
97 
98  /** \brief Returns the number of characters required to display the
99  exponent of \c x in scientific mode
100 
101  This returns 2 or 3, depending on whether or not the absolute
102  magnitude of the exponent is greater than or equal to 100. It
103  uses <tt>stringstream</tt> to convert the number to a string and
104  counts the number of characters directly.
105  */
106  size_t size_of_exponent(double x);
107 
108  /** \brief Convert a double to a string using a specified format
109  */
110  std::string dtos(double x, std::ostream &format);
111 
112  /** \brief Convert a string to an integer
113 
114  This function is now just a wrapper for <tt>std::stoi</tt>.
115  */
116  int stoi(std::string s);
117 
118  /** \brief Convert a string to an integer without throwing an
119  exception
120  */
121  int stoi_nothrow(std::string s, int &result);
122 
123  /** \brief Convert a string to a size_t
124 
125  If \c err_on_fail is true and the conversion fails, this
126  function calls the error handler, otherwise this function just
127  returns zero.
128  */
129  size_t stoszt(std::string s);
130 
131  /** \brief Convert a string to a size_t without throwing an
132  exception
133 
134  If \c err_on_fail is true and the conversion fails, this
135  function calls the error handler, otherwise this function just
136  returns zero.
137  */
138  int stoszt_nothrow(std::string s, size_t &result);
139 
140  /** \brief Convert a string to a boolean value
141 
142  This returns true if only if the string has at least one
143  character and the first non-whitespace character is either \c t,
144  \c T, or one of the numbers 1 through 9.
145 
146  If \c err_on_fail is true and the conversion fails, this
147  function calls the error handler, otherwise this function just
148  returns false.
149  */
150  bool stob(std::string s, bool err_on_fail=true);
151 
152  /** \brief Convert a string to a double
153 
154  This function is now just a wrapper for <tt>std::stod</tt>.
155 
156  \warning Because of the presence of <tt>std::stod()</tt> in
157  C++11, you may have to explicitly provide the
158  namespace, i.e. <tt>o2scl::stod()</tt> in your code.
159  */
160  double stod(std::string s);
161 
162  /** \brief Convert a string to a double returning non-zero
163  value for failure
164  */
165  int stod_nothrow(std::string s, double &result);
166 
167  /** \brief Find out if the number pointed to by \c x has a minus sign
168 
169  This function returns true if the number pointed to by \c x has
170  a minus sign, determining this by converting the number to a
171  string. It is useful, for example, in distinguishing "-0.0" from
172  "+0.0".
173  */
174  bool has_minus_sign(double *x);
175 
176  /** \brief Return true if the string \c s is likely a integral or
177  floating point number
178 
179  \note The test employed is not exhaustive and this function may
180  return \c true for some numbers and may return \c false for some
181  non-numbers.
182  */
183  bool is_number(std::string s);
184 
185  /** \brief Convert a formula to a double
186 
187  This function removes all quotes and apostrophes from the string
188  and then uses \ref o2scl::calculator to convert strings like
189  "-1.0e-3", "1.0/3.0" and "exp(cos(-1.0e-2))" to floating point
190  numbers.
191  */
192  double function_to_double(std::string s);
193 
194  /** \brief Convert a formula to a double and return an integer to
195  indicate success or failure
196 
197  This function removes all quotes and apostrophes from the string
198  and then uses \ref o2scl::calculator to convert strings like
199  "-1.0e-3", "1.0/3.0" and "exp(cos(-1.0e-2))" to floating point
200  numbers.
201  */
202  int function_to_double_nothrow(std::string s, double &result);
203 
204  /** \brief Split a string into words using whitespace for delimiters
205  and (partially) respecting quotes
206 
207  This function separates a string into words, and handles words
208  that begin with a <tt>"</tt> by adding more words until finding
209  one which ends with another <tt>"</tt>. Strings like
210  \code
211  this is a test
212  \endcode
213  get parsed as "this", "is", "a", "test" and strings like
214  \code
215  "this is" a test
216  \endcode
217  get parsed as "this is", "a", "test".
218 
219  This is used to reformat command descriptions and help text for
220  the screen width in cli::comm_option_help(), to process lines
221  read from a file in cli::comm_option_run(), and to process input
222  in cli::run_interactive().
223 
224  \note The parsing algorithm here is simple-minded and can
225  produce unexpected results in several ways. For example, it may
226  not properly handle nested quotes, like <tt>"""test" test2"
227  test3"</tt>.
228 
229  \future Replace with a better algorithm
230  \future Add user-specified delimiters?
231  */
232  void split_string(std::string str, std::vector<std::string> &sv);
233 
234  /** \brief Split a string into parts using a delimiter
235  */
236  int split_string_delim(std::string str, std::vector<std::string> &list,
237  char delim);
238 
239  /** \brief Rewrap a string into a single column, avoiding
240  strings less than a particular number of characters
241  */
242  void rewrap(std::string str, std::vector<std::string> &sv,
243  size_t ncol=79);
244 
245  /** \brief Rewrap a string into a single column, avoiding
246  strings less than a particular number of characters
247 
248  This function is used to format the help output
249  in \ref o2scl::cli .
250  */
251  void rewrap_keep_endlines(std::string str, std::vector<std::string> &sv,
252  size_t ncol=79);
253 
254  /** \brief Convert a string-based list of unsigned integers
255  to a list
256  */
257  template<class size_vec_t>
258  int string_to_uint_list(const std::string &x,
259  size_vec_t &list) {
260 
261  list.clear();
262  std::vector<std::string> ranges;
263  size_t k=0;
264  while (k<x.length()) {
265  size_t loc=x.find(',',k);
266  if (loc!=std::string::npos) {
267  std::string stemp=x.substr(k,loc-k);
268  ranges.push_back(stemp);
269  k+=stemp.length()+1;
270  } else {
271  if (k<x.length()) {
272  ranges.push_back(x.substr(k,x.length()-k));
273  }
274  k=x.length();
275  }
276  }
277  size_t uitmp, uitmp2;
278  for(size_t j=0;j<ranges.size();j++) {
279  if (ranges[j].find('-')==std::string::npos) {
280  int ret=stoszt_nothrow(ranges[j],uitmp);
281  if (ret!=0) return ret;
282  list.push_back(uitmp);
283  } else {
284  size_t loc=ranges[j].find('-');
285  std::string sstart=ranges[j].substr(0,loc);
286  std::string send=ranges[j].substr(loc+1,ranges[j].size()-loc);
287  int ret=stoszt_nothrow(sstart,uitmp);
288  if (ret!=0) return ret;
289  ret=stoszt_nothrow(send,uitmp2);
290  if (ret!=0) return ret;
291  for(size_t jk=uitmp;jk<=uitmp2;jk++) {
292  list.push_back(jk);
293  }
294  }
295  }
296 
297  return 0;
298  }
299  //@}
300 
301 #ifndef DOXYGEN_NO_O2NS
302 }
303 #endif
304 
305 #endif
306 
o2scl::is_number
bool is_number(std::string s)
Return true if the string s is likely a integral or floating point number.
o2scl::string_to_uint_list
int string_to_uint_list(const std::string &x, size_vec_t &list)
Convert a string-based list of unsigned integers to a list.
Definition: string_conv.h:258
o2scl::dtos
std::string dtos(const fp_t &x, int prec=6, bool auto_prec=false)
Convert a double to a string.
Definition: string_conv.h:77
o2scl::has_minus_sign
bool has_minus_sign(double *x)
Find out if the number pointed to by x has a minus sign.
o2scl::btos
std::string btos(bool b)
Convert a boolean value to a string.
O2SCL_ERR2
#define O2SCL_ERR2(d, d2, n)
Set an error, two-string version.
Definition: err_hnd.h:281
o2scl::stoi
int stoi(std::string s)
Convert a string to an integer.
o2scl
The main O<span style='position: relative; top: 0.3em; font-size: 0.8em'>2</span>scl O$_2$scl names...
Definition: anneal.h:42
o2scl::stoszt
size_t stoszt(std::string s)
Convert a string to a size_t.
o2scl::stod
double stod(std::string s)
Convert a string to a double.
o2scl::rewrap_keep_endlines
void rewrap_keep_endlines(std::string str, std::vector< std::string > &sv, size_t ncol=79)
Rewrap a string into a single column, avoiding strings less than a particular number of characters.
o2scl::exc_einval
@ exc_einval
invalid argument supplied by user
Definition: err_hnd.h:59
o2scl::stoi_nothrow
int stoi_nothrow(std::string s, int &result)
Convert a string to an integer without throwing an exception.
o2scl::rewrap
void rewrap(std::string str, std::vector< std::string > &sv, size_t ncol=79)
Rewrap a string into a single column, avoiding strings less than a particular number of characters.
o2scl::size_of_exponent
size_t size_of_exponent(double x)
Returns the number of characters required to display the exponent of x in scientific mode.
o2scl::stoszt_nothrow
int stoszt_nothrow(std::string s, size_t &result)
Convert a string to a size_t without throwing an exception.
o2scl::itos
std::string itos(int x)
Convert an integer to a string.
o2scl::stod_nothrow
int stod_nothrow(std::string s, double &result)
Convert a string to a double returning non-zero value for failure.
o2scl::split_string
void split_string(std::string str, std::vector< std::string > &sv)
Split a string into words using whitespace for delimiters and (partially) respecting quotes.
o2scl::ptos
std::string ptos(void *p)
Convert a pointer to a string.
o2scl::function_to_double
double function_to_double(std::string s)
Convert a formula to a double.
o2scl::split_string_delim
int split_string_delim(std::string str, std::vector< std::string > &list, char delim)
Split a string into parts using a delimiter.
o2scl::stob
bool stob(std::string s, bool err_on_fail=true)
Convert a string to a boolean value.
o2scl::function_to_double_nothrow
int function_to_double_nothrow(std::string s, double &result)
Convert a formula to a double and return an integer to indicate success or failure.
o2scl::szttos
std::string szttos(size_t x)
Convert a size_t to a string.

Documentation generated with Doxygen. Provided under the GNU Free Documentation License (see License Information).