In C++03 you can use std::ostringstream
class to format a 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();
^^^^^^^^^ // this will yield a formatted string that oss contains
}
In C++11 you can use std::to_string and operator+
to 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 you want to specify format, again, you should look into string stream.