Hi
Is there a c++ equivalent function to the c-function 'sprintf'?
Thnaks
Hi
Is there a c++ equivalent function to the c-function 'sprintf'?
Thnaks
You can also check out boost::format, which can be easier to work with than stringstream
thank you, that looks much more convenient!
I guess it's rather ::sprintf (with extern "C" { / #include <stdio.h> / }).
But if you want some safety, you'd use ::snprintf, and if you don't want to implement the safety yourself, you could rather use lisp^W std:stringstream.
std:stringstream s; s<<"Hi "<<world<<std::endl;
std::string str =s.str();
const char* cstr=s.c_str();
C functions are in the "root" namespace; to avoid
refering a different object in the current namespace, it's advised (in various style guides) to qualify C functions.
Then, using a function without declaring it would make a sane compiler complain, so it's good practice to include some header declaring it before using it.
The is the C++ group here, so the C header <stdio.h> is to be
included using <cstdio> and its content is accessible only within
the 'std' namespace.
This is works well, works like a sprintf for c++
Code:std::string string_format(const std::string &fmt, ...) { int n, size=100; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) return str; if (n > -1) size=n+1; else size*=2; } }
Bookmarks