将时间戳复制到字符串

jip*_*pot 0 c++

我想将时间戳复制到字符串temp.

cout << "Begin time: " << ctime(&timer);
Run Code Online (Sandbox Code Playgroud)

成功打印出来:

开始时间:2014年3月3日星期一17:40:04

这是我想要的格式.

我目前的代码; 然而,编译,但没有打印出来.

sprintf(temp, "Begin time: %d\n", ctime(&timer));
cout << temp << endl;
Run Code Online (Sandbox Code Playgroud)

tim*_*rau 5

由于返回值ctime()看起来像一个字符串,你应该写

sprintf(temp, "Begin time: %s\n", ctime(&timer));
Run Code Online (Sandbox Code Playgroud)

请注意%sfor字符串而不是%d十进制整数.

但是,为了确保不要超出缓冲区,最好使用ostringstreamstring.

std::ostringstream strm;
strm << "Begin time: " << ctime(&timer) << "\n";
std::string temp(strm.str());
cout << temp << endl;
Run Code Online (Sandbox Code Playgroud)