gpt4 book ai didi

c++ - 如何在 C++ 中使用字符串修饰符创建新字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:59 25 4
gpt4 key购买 nike

我想以某种格式将时间戳写入文件。

有没有一种方法可以使用修饰符创建一个新字符串(参见下面的 printf 代码)?还是有另一种在 TextStream 中使用字符串修饰符的方法?

printf("%02d-%02d-%02d_%02d:%02d:%02d.%02d\n", 
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

最佳答案

一个类型安全的替代方案,不用担心缓冲区大小,将使用 IO manipulators直接在输出流上或在 std::ostringstream 上:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

int main()
{
std::ostringstream s;
s << std::setfill('0')
<< std::setw(2) << 1 << ':' // st.wYear, etc
<< std::setw(2) << 97 << ':'
<< std::setw(2) << 4;

std::cout << s.str() << "\n";

return 0;
}

此外,之前的一个答案说明了将 int 转换为 std::string 的方法:Append an int to a std::string

关于c++ - 如何在 C++ 中使用字符串修饰符创建新字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11835224/

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