4

我正在尝试编写一个将日期作为字符串返回的函数。我是这样处理的:

string date() // includes not listed for sake of space, using namespace std
{
    tm timeStruct;
    int currentMonth = timeStruct.tm_mon + 1;
    int currentDay   = timeStruct.tm_mday;
    int currentYear  = timeStruct.tm_year - 100;
    string currentDate = to_string(currentMonth) + "/" + to_string(currentDay) + "/" + to_string(currentYear);
    return currentDate;
}

这给出了四个编译时错误。其中 1 个:

to_string was not declared in this scope

其中3个:

Function to_string could not be resolved

每次使用 to_string 一个。

根据互联网上的其他任何地方,这段代码应该可以工作。有人可以对这个主题有所了解吗?

4

2 回答 2

3

正如评论中提到的,您尝试使用的内容需要 C++11。这意味着既支持 C++11(例如 GCC 4.7+)的编译器,也可能手动启用 C++11(例如 flag -std=c++11),所以如果您认为它应该适合您,请检查这两个。

如果您遇到不支持 C++11 的编译器,您可以使用以下内容通过常规 C++ 实现您想要的:

string date()
{
    tm timeStruct;
    int currentMonth = timeStruct.tm_mon + 1;
    int currentDay   = timeStruct.tm_mday;
    int currentYear  = timeStruct.tm_year - 100;
    char currentDate[30];
    sprintf(currentDate, "%02d/%02d/%d", currentMonth, currentDay, currentYear);
    return currentDate; // it will automatically be converted to string
}

请注意,对于 Day 和 Month 参数,我曾经%02d强制它显示至少 2 位数字,因此5/1实际上将表示为05/01. 如果你不想这样,你可以%d改用它,它的行为就像你原来的to_string. (我不确定您使用的是什么格式currentYear,但您可能还想使用其中一个%02d%04d该参数)

于 2013-05-26T22:35:25.907 回答
1

std::to_string是 C++11 的一部分并且在<string>标题中。以下代码适用于 g++ 4.7,以及最新版本的 clang 和 VC++。如果使用这些内容编译文件对您不起作用,您要么为 C++11 错误地调用了编译器,要么使用了对 C++11 支持不足的编译器版本。

#include <string>

int main() {
  int i;
  auto s = std::to_string(i);
}

然而,在 C++11 中有更好的打印日期的方法。这是一个打印当前日期的程序(ISO 8601 格式)。

#include <ctime>     // time, time_t, tm, localtime
#include <iomanip>   // put_time
#include <iostream>  // cout
#include <sstream>   // stringstream
#include <stdexcept> // runtime_error
#include <string>    // string

std::string date() {
  static constexpr char const *date_format = "%Y-%m-%d"; // ISO 8601 format

  auto t = std::time(nullptr);
  if (static_cast<std::time_t>(-1) == t) {
    throw std::runtime_error{"std::time failed"};
  }

  auto *cal = std::localtime(&t);
  if (nullptr == cal) {
    throw std::runtime_error{"std::localetime failed"};
  }

  std::stringstream ss;
  ss << std::put_time(cal, date_format);
  return ss.str();
}

int main() { std::cout << date() << '\n'; }

不幸的是 gcc 4.8 似乎缺少put_time(当然 VC++ 目前缺少constexpr通用初始化程序,但这很容易解决。VC++ 有put_time)。

于 2013-05-26T23:08:30.860 回答