String into integer in C++ -
i have string value : 2014-04-14
i want convert integer 20140414
i know string in integer can done
std::string mystring = "45"; int value = atoi(mystring.c_str()); //value = 45
but don't know how remove -
sign.
using streams:
std::istringstream iss("2014-04-14");
then if have c++11, can use new get_time
io manipulator:
std::tm tm; if (iss >> get_time(&tm, "%y-%m-%d")) ...
the std::tm
structure has extracted values, namely:
- years since 1900 stored in
tm.tm_year
- months since january (so 0..11) stored in
tm.tm_mon
- day of month (1..31) stored in
tm.tm_mday
so, desired value is:
int value = (tm.tm_year + 1900) * 10000 + (tm.tm_mon + 1) * 100 + tm.tm_mday;
alternatively, or c++03, can parse values out of istringstream
yourself:
int year, month, day; char c; if (iss >> year >> c && c == '-' && iss >> month >> c && c == '-' && iss >> day) { int value = year * 10000 + month * 100 + day; ... use value ... } else std::cerr << "invalid date\n";
Comments
Post a Comment