【问题标题】:C++ Get Current date output weird resultC ++获取当前日期输出奇怪的结果
【发布时间】:2012-08-18 17:44:01
【问题描述】:

我的输出是不可读的,我想做的就是将日月年分配到一个字符串中。

如果我通过 now->tm_year+1900 计算它们,它可以工作,但如果我将它分配给一个字符串并稍后 cout,它会像这样输出。如何更改我的代码,以便我可以将值分配给字符串,而不会在以后丢失 cout 的引用。

终端:

Date is 

我的代码:

int main()
{
//get today date
string year,month,day;

/* Output 6 month frame for appointment booking*/
 time_t t = time(0);   // get time now
 struct tm * now = localtime( & t );

year = now->tm_year + 1900;
month = now->tm_mon + 1;
day = now->tm_mday;

cout << "Date is " << year << month << day << endl;

return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    您不能将整数分配给字符串(嗯,您可以,但它并不完全符合您的预期);你必须先转换它们:

    std::string year = std::to_string(now->tm_year + 1900);
    

    其他选项包括将数字存储为整数;你也可以打印整数:

    int year = now->tm_year + 1900;
    

    【讨论】:

    • 好的,我现在明白了。我使用的数据类型错误,使用 int 解决了这个问题。谢谢。
    • 如果此答案对您有帮助,请将您的问题标记为已回答。
    【解决方案2】:

    您可以在代码文件中写入int 而不是string

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      相关资源
      最近更新 更多