Search code examples
c++printfsstreammanipulators

Is there method of in place string manipulation native to the mingw libraries that doesn't involve i/o streams


I am attempting to construct a serial number of a certain format. This number will be entered into a database. At this point I am having to use sprintf, but I would like a native C++ method for it.

Here is sample code:

int i;

sprintf(buffer, "%03d", i);

The integer will be anywhere from 1 to 3 digits. The format needs to look like this:

001, ... 013, ... 101, ... etc.

The "serial number" has the format:

AAAAA001, ... AAAAA013, ... AAAAA101, etc.

So the question is, is there a way to do this that is native to C++ without having to use iostream manipulators and that is included in the mingw-w64 libraries. Or does it require something like boost libraries?

Another way to put it: is there a drop-in replacement in C++ for the C sprintf function?

Edit based upon comments:

So there is nothing as simple as....

int i;
string buffer;

sprintf(buffer, "%03d", i);

I realize that this does not work, but it gives the thought anyway. There is no way to operate directly on a string class object with a method that serves the function of sprintf?


Solution

  • I'm taking aruisdante's answer as the best answer to the question although it is a stream which I initially found undesirable.

    I think the real question you have to answer first is "why do you not want >to use sstream "? Without establishing that first, it's a bit of an >XYProblem, since sstream will certainly solve the given problem clearly, >type-safely and relatively efficiently. – aruisdante

    My understanding of streams was too narrow. It looks like a stringstream should work well for my application.

    Thanks again.