在c ++中将时间附加到字符串时出现访问冲突错误

Tom*_*Tom 4 c++ string initialization append

请使用以下代码:

#inlcude <iostream>
#include <time.h>
using namespace std;

int main(int argc, char* argv[])
{
    time_t t;
    time(&t);

    string s = "file" + t;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在线

string s = "file" + t
Run Code Online (Sandbox Code Playgroud)

我收到访问冲突错误.

如果我改为:#inlcude using namespace std;

int main(int argc, char* argv[])
{
    time_t t;
    time(&t);
    int x = t;

    string s = "file" + x;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我仍然得到同样的错误.怎么了?当然将int附加到字符串不能抛出访问冲突?

Ben*_*ley 5

"file" + t
Run Code Online (Sandbox Code Playgroud)

这根本不符合你的期望. "file"是一个char数组.您不能将整数添加到char数组.但是您可以向指针添加整数,并且数组可以隐式转换为指针.价值t可能在数十亿美元的某个地方.因此,"file" + t一些指针的结果是距离char数组大约十亿字节"file".然后尝试使用该指针初始化一个字符串.您不太可能合法访问此内存位置,因此您会遇到访问冲突.无论如何,它都是未定义的行为.如果你这样做了:

std::string s("file");
s += t;
Run Code Online (Sandbox Code Playgroud)

您可能会遇到正确的编译器错误.试试这个:

std::string s("file");
s += std::to_string((long long)t);
Run Code Online (Sandbox Code Playgroud)

如果您无法使用该功能(它是C++ 11中的新功能),那么您可以使用stringstreams:

std::ostringstream oss;
oss << "file" << t;
std::string s(oss.str());
Run Code Online (Sandbox Code Playgroud)