Converting Time string to float
Jun 5, 2013 at 1:45pm UTC
I have a vector<string> of times that I want to convert to vector<double>. The time string is in the form 00:00.000. Is there a STL or something like it algorithm or function to do this, otherwise what would be the best way to do this with a function.
-Thank you
Jun 5, 2013 at 3:26pm UTC
How do you expect the time string to be converted to a double? I can't possibly imagine what this means.
Jun 5, 2013 at 3:28pm UTC
To its equivalent in seconds.
Jun 5, 2013 at 5:11pm UTC
Use the std::transform from algorithms:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
#define STR(x) #x << '=' << x
template <class C>
std::ostream&
operator <<(std::ostream& os, const std::vector<C>& v)
{
os << '{' ;
for (typename std::vector<C>::const_iterator it = v.begin();
it != v.end();
++it)
{
if (it != v.begin())
os << ',' ;
os << *it;
}
os << '}' ;
return os;
}
/** \brief convert a time string to seconds.
*
* Convert a string in format mm:ss.sss to seconds.
* eg 12:34.567 => 754.567
* eg 34.567 => 34.567
* \todo this can be made more bullet-proof
*/
double
string_to_double(const std::string &s)
{
std::string str = s;
const char *cp = strchr(str.c_str(), ':' );
if (cp == 0) {
double seconds = atof(str.c_str());
return seconds;
}
else {
unsigned minutes = atoi(str.c_str());
double seconds = atof(++cp);
seconds += 60.0 * minutes;
return seconds;
}
}
int
main(int ,char ** argv)
{
std::cout << argv[0] << " start" << std::endl;
std::vector<std::string> strings;
strings.push_back("00:00.000" );
strings.push_back("00:00.001" );
strings.push_back("10:00.000" );
std::cout << STR(strings) << std::endl;
std::vector<double > doubles;
doubles.resize(strings.size());
std::transform(strings.begin(), strings.end(),
doubles.begin(), string_to_double);
std::cout << STR(doubles) << std::endl;
std::cout << argv[0] << " finish" << std::endl;
}
./test_time_string_to_float start
strings={00:00.000,00:00.001,10:00.000}
doubles={0,0.001,600}
./test_time_string_to_float finish
Topic archived. No new replies allowed.