c++ to_string日期错误

c++ to_string error with date

本文关键字:日期 错误 string to c++      更新时间:2023-10-16

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

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

会产生四个编译时错误。

to_string was not declared in this scope

和其中3个:

Function to_string could not be resolved

每使用一个to_string。

根据互联网上的其他地方,这段代码应该可以工作。有人能解释一下这个问题吗?

正如在评论中提到的,您尝试使用的东西需要c++ 11。这意味着编译器既支持c++ 11(例如GCC 4.7+),也可能手动启用c++ 11(例如标记-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为该参数)

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