返回整数值作为日期格式的字符串

时间:2014-04-15 17:54:59

标签: c++ string int

我的函数有三个整数值,分别代表年,月和日。我想在中间用破折号' - '返回这些值,就像在普通日期格式中一样。

例如:

int main() {
    cout << myfunction() << endl; // this should display like this 2014-04-15
}

string myfunction() {
    int year = 2014;
    int month = 04;
    int day = 15;
    // I want to return this value like this
    return year-month-day;//2014-04-15
}

有人可以帮助我吗?

7 个答案:

答案 0 :(得分:2)

#include <sstream>
#include <iomanip>    

...

std::stringstream ss;
ss << std::setfill('0') << std::setw(4) << year << "-"
   << std::setw(2) << month << "-" << std::setw(2) << day;
return ss.str();

答案 1 :(得分:1)

在C ++ 03中,您可以使用std::ostringstream类使用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
}

在C ++ 11中,您可以使用std::to_stringoperator+来连接字符串:

#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;
}

但是to_string不提供格式化选项。如果你想再次指定格式,你应该查看字符串流。

答案 2 :(得分:1)

另外,如果您没有C ++ 11,请查看boost :: lexical_cast(...),或者如果您不想要提升,请查看stringstream。

stringstream ss;
ss << first << "-" << second << "-" << third << endl;
return ss.str();

必须工作。

答案 3 :(得分:1)

ostringstream oss;
oss << year << '-' << month << '-' << day;

return oss.str();

答案 4 :(得分:1)

您可以使用字符串流。

string myfunction(){
    int year=2014;
    int month=04;
    int day=15;
    stringstream ss;
    ss << year << "-" << month << "-" << day;
    return ss.str();
}

请勿忘记添加sstream标题。

答案 5 :(得分:0)

如果您不想使用STL,您还可以使用C风格的函数_itoa。以下是文档的链接:

http://msdn.microsoft.com/en-us/library/yakksftt.aspx

但我确实建议你像其他人一样建议使用stringstream。

答案 6 :(得分:0)

即使在C ++代码中,我也喜欢printf - 就像格式说明符一样(在这种情况下,与sprintf()一起使用)。

您可能需要考虑这个可编辑的代码:

#include <stdio.h>
#include <iostream>
#include <string>

std::string ToString(int year, int month, int day) {
    char buffer[11];
    // YYYY-MM-DD
    // 1234567890
    //          10 + NUL --> 11 characters in buffer

    sprintf(buffer, "%04d-%02d-%02d", year, month, day);
    // sprintf_s on MSVC would be better (and it implicitly gets the dest buffer size).

    return buffer;
}

int main() {
    std::cout << ToString(2014, 4, 15) << std::endl;
}

根据要求输出2014-04-15


<强> PS
如果您想使用C ++字符串流(来自<sstream>),那么您应该注意 padding ,其前导0个月和天数有一位数。为此,请考虑this StackOverflow question及相关答案。关键点是使用setfill('0')setw(2)进行填充。