Re: Using string correctly
On Feb 27, 4:20 am, cbarr...@ix.netcom.com (Carl Barron) wrote:
Felix Bollenbeck <feb...@gmx.de> wrote:
I bet there is a more elegant (more OO-like) alternative to this C
like construct
char buff[255];
sprintf(buff,"out%03d.tif",i++);
writer->SetFileName(buff);
Can anybody point me to the right direction - Im new to C++
std::ostringstream os
os << "out" << std::setfill('0') << std::setw(3) << i++ << ".tif";
Am I the only one who prefers changing the non-volatile flags
directly, rather than using manipulators, in such cases.
Something like:
std::ostringstring tmp ;
tmp.fill( '0' ) ;
tmp << "out" << std::setw(3) << i++ << ".tif" ;
About the only standard manipulator I ever use is setw; in my
mind, a manipulator doesn't permanently change the formatting
options. (My custom manipulators have class types which restore
the initial state in their destructors, at the end of the full
expression.)
writer->SetFileName(os.str().c_str));
this is a C++ way. Since the string involved is 10 chars long it
should be sufficiently fast. but with a small string like this
and a C api for the string,
char buff[11]; // the string length + 1 == 11.
if(i < 1000)
{
sprintf(...);
writer->SetFileName(buf);
}
else throw some_error();
is probably more efficient and safe.
Until some maintenance programmer changes something. (There's
also no reason to expect it to be faster that ostrstream on a
fixed length buffer. And in this case, of course, the time
necessary to create or access the file whose name he's
generating will probably be so much greater that even the extra
allocations ostringstream must make will probably get lost in
the noise.)
if you have snprintf() it is safer as there is no chance for a
buffer overrun, [not present in this example since we are creating
a fixed length string]
The chance is always present as long as there is program
maintenance. Either snprintf or ostrstream check length, and
should be preferred; ostrstream also has the advantage of using
the standard C++ idiom, which every C++ programmer should know,
rather than some exotic and obscure meta-language only known to
us old fogeys who come from C.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]