I want to refactor some printf/sprintf/fprintf statements into ostream/sstream/fstream statements. The code in question pretty-prints a series of integers and floating-point numbers, using whitespace padding and fixed numbers of decimal points.
It seems to me that this would be a good candidate for a Martin Fowler style writeup of a safe, step-by-step refactorings, with important gotchas noted. The first step, of course, is to get the legacy code into a test harness, which I have done.
What slow and careful steps can I take to perform this refactoring?
Basic mechanics of the conversion:
printf-style clause%w.pfor%w.pe, wherewis the field width andpis the number of digits of precision, into<< setw(w) << setprecision(p) << fixed.printf-style clause%wdor%wi, wherewis the field width, into<< setw(w)."\n"toendlwhere appropriate.Process for
printf:char[](let’s call ittext) with enough total width.printf(...)tosprintf(text, ...), and usecout << textto actually print the text.Process for
fprintf:printf, but use the appropriatefstreaminstead ofcout.FILEobject that you do not want to refactor at this time, it gets a little sticky (but can be done).Process for
sprintf:stringstreamand streaming the contents of thechar[]you are writing to into that. If you are still intending to extract achar*from it, you can dostd::stringstream::str().c_str().Common instructions:
*printfandchar[]declarations as necessary when finished.