0

I want to write a timestamp to a file in a certain format.

Is there a way to create a new string using modifiers (see printf code below)? Or is there another way to use string modifiers in a TextStream?

printf("%02d-%02d-%02d_%02d:%02d:%02d.%02d\n", 
       st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Makaku00
  • 121
  • 5
  • 14
  • Would you elaborate on your issue? Is this a program which intersects C & C++? Could this be possibly a C example of what you'd like to do in C++? This is an issue I'm taking up, dealing with code examples in other languages than the one the advice is asking for without clarification of the intent. Thanks a bunch! – ChiefTwoPencils Aug 06 '12 at 20:48
  • I wanted use a string stream to write a string to a file in the same format as the printf in my example. Using sprintf makes this possible! – Makaku00 Aug 07 '12 at 07:33

2 Answers2

5

A type-safe alternative, with no concerns over buffer size, would be to use IO manipulators either on the output stream directly or on 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;
}

Additionally, a previous answer that illustrates approaches for getting an int into a std::string: Append an int to a std::string

Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

If you use sprintf instead of printf, the string you want is written to a char buffer rather than printed.

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

You can also use the Boost Format library.

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
  • Aha!! Thanks.. I'm not really familiar with C++. I had tried sprintf before but i apparently used it incorrectly! – Makaku00 Aug 06 '12 at 20:23