2 * @brief string conversion utility functions for omega
4 /* Copyright 1999,2000,2001 BrightStation PLC
5 * Copyright 2003,2004,2006,2010,2011 Olly Betts
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
28 #include <stdio.h> // for sprintf/snprintf
35 // This ought to be enough for any of the conversions below.
39 #define CONVERT_TO_STRING(FMT) \
41 int len = SNPRINTF(buf, BUFSIZE, (FMT), val);\
42 if (len == -1 || len > BUFSIZE) return string(buf, BUFSIZE);\
43 return string(buf, len);
45 #define CONVERT_TO_STRING(FMT) \
47 buf[BUFSIZE - 1] = '\0';\
48 sprintf(buf, (FMT), val);\
49 if (buf[BUFSIZE - 1]) abort(); /* Uh-oh, buffer overrun */ \
54 string_to_int(const string
&s
)
56 return atoi(s
.c_str());
60 double_to_string(double val
)
62 CONVERT_TO_STRING("%f")
66 date_to_string(int y
, int m
, int d
)
69 if (y
< 0) y
= 0; else if (y
> 9999) y
= 9999;
70 if (m
< 1) m
= 1; else if (m
> 12) m
= 12;
71 if (d
< 1) d
= 1; else if (d
> 31) d
= 31;
73 int len
= SNPRINTF(buf
, sizeof(buf
), "%04d%02d%02d", y
, m
, d
);
74 if (len
== -1 || len
> int(sizeof(buf
))) return string(buf
, sizeof(buf
));
75 return string(buf
, len
);
77 buf
[sizeof(buf
) - 1] = '\0';
78 sprintf(buf
, "%04d%02d%02d", y
, m
, d
);
79 if (buf
[sizeof(buf
) - 1]) abort(); /* Uh-oh, buffer overrun */
87 string::size_type first_nonspace
;
88 first_nonspace
= s
.find_first_not_of(" \t\r\n\v");
89 if (first_nonspace
== string::npos
) {
90 // String is all whitespace.
93 // Remove any trailing whitespace.
94 string::size_type len
= s
.find_last_not_of(" \t\r\n\v");
95 assert(len
!= string::npos
);
96 if (len
< s
.size() - 1)
98 // Remove any leading whitespace.
99 if (first_nonspace
> 0)
100 s
.erase(0, first_nonspace
);