I'm trying to fully understand how to use ostringstream
to modernize some code that uses sprintf
. The problem is in replacing test code that generates random or sequential data. Here's a simplified example:
char num[6], name[26];
sprintf(num, "%05d", i);
sprintf(name, "Customer # %d", i);
Leaving aside the minutia of length calculation, copying the result to the array and null-termination, the num
conversion is straightforward:
ostringstream ostr;
ostr << setw(len) << setfill('0') << i;
For example, given i
as 123, the result is "00123".
However, for the name
, which is actually a mixture of a char-string and an integer, I can't figure how to replicate what sprintf
appears to do so easily.
I tried variations of this:
ostr << setw(len) << left << "Customer # " << i << setfill(' ');
Given the same value for i
, the result was always "Customer # 123", i.e., the integer always right justified, no matter what combination of left
, right
or internal
, or the placement of the various parts. It seems the only solution (I haven't tried it yet), is to first concatenate the "Customer # " and the i
onto a separate ostringstream
and then insert that left justified to the ostr
variable. Am I missing something? Is there some other way?
Correction: as discussed in the comments, in simplifying the example I overlooked a second sprintf
that was actually responsible for right-padding the name. So a second output to the ostringsteam
is also needed to accomplish that.