c++ to_string日期错误
c++ to_string error with date
我正在尝试编写一个返回日期作为字符串的函数。我是这样做的:
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
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 无法在初始化时将"日期"转换为"int"作为错误
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- Visual 2015 上的 std::get_time 不会在错误的日期失败
- "日期":'class'类型重新定义:错误(日历.cpp文件错误)
- 该代码的主要错误是什么,用于确定n`天后日期
- 在 CLI 中转换日期时间time_t错误处理C++是否安全
- C++ <ctime> 打印错误的日期
- 这是Zeller程序的代码.除了1111年2月31日、1111年6月31日这一通常是错误的日期外,一切都很顺利
- NTP服务器总是返回相同的错误日期(窗口)
- 提升公历日期格式会产生错误的结果
- C++提升库 - 正确处理日期序列内存分配错误
- c++ to_string日期错误
- c++ boost regex日期错误
- Boost 1.53本地日期时间编译器错误使用-std=c++0x
- Visual Studio 2012中Boost posix日期和时间的编译错误