c++ - Return integer value as string for date formatting -
this question has answer here:
i have function has 3 integer values, representing year, month , day. want return these values dashes '-' in between, in common date format.
e.g.:
int main() { cout << myfunction() << endl; // should display 2014-04-15 } string myfunction() { int year = 2014; int month = 04; int day = 15; // want return value return year-month-day;//2014-04-15 } can me?
in c++03 can use std::ostringstream class format string using operator<< :
#include <string> #include <sstream> #include <iomanip> std::string myfunction() { int year=2014; int month=04; int day=15; std::ostringstream oss; oss << year << "-" << std::setw(2) << std::setfill('0') << month << "-" << day; return oss.str(); ^^^^^^^^^ // yield formatted string oss contains } in c++11 can use std::to_string , operator+ concatenate strings:
#include <string> std::string myfunction() { int year=2014; int month=04; int day=15; std::string s = to_string( year) + "-" + to_string(month) + "-" + to_string(day); return s; } however to_string doesn't offer formatting option. if want specify format, again, should string stream.
Comments
Post a Comment