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

Mak*_*u00 0 c++ string writetofile

我想以某种格式写一个文件的时间戳.

有没有办法使用修饰符创建一个新的字符串(请参阅下面的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);
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 5

不考虑缓冲区大小的类型安全替代方案是在输出流上直接或使用IO操纵器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;
}
Run Code Online (Sandbox Code Playgroud)

另外,之前的答案说明了获取inta的方法std::string:将int附加到std :: string