gpt4 book ai didi

c++ - 如何将系统时间附加到字符串变量

转载 作者:行者123 更新时间:2023-11-28 05:33:20 24 4
gpt4 key购买 nike

#include<iostream>
#include<ctime>
#include<string>
using namespace std;

int main()
{
string NowTime;
time_t now;

struct tm nowLocal;

now=time(NULL); // get the time from the OS

nowLocal=*localtime(&now);

NowTime = nowLocal.tm_hour + ':' + nowLocal.tm_min + ':' + nowLocal.tm_sec;
cout<< NowTime;
}

当我运行程序时,它没有任何显示,有人可以帮助我吗?我是编程新手。

最佳答案

如果你尝试

cout << nowLocal.tm_hour + ':' + nowLocal.tm_min + ':' + nowLocal.tm_sec;

你会看到一个整数,而不是任何类似时间的东西。
这是因为它是五个整数的总和 - 字符被提升为整数,然后全部相加。

最简单的解决方法是根本不构建字符串,而是单独输出各个部分:

cout << nowLocal.tm_hour << ':' << nowLocal.tm_min << ':' << nowLocal.tm_sec;

否则,您需要将这些数字转换为字符串:

NowTime = std::to_string(nowLocal.tm_hour) + ':' + std::to_string(nowLocal.tm_min) + ':' + std::to_string(nowLocal.tm_sec);

或者,您可以使用 std::ostringstream,它的工作方式与 std::cout 和其他流一样,但写入 std::字符串:

std::ostringstream ss;
ss << nowLocal.tm_hour << ':' << nowLocal.tm_min << ':' << nowLocal.tm_sec;
NowTime = ss.str();

关于c++ - 如何将系统时间附加到字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38900395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com