C ++ equivalent to sprintf?

I know that std::cout is the equivalent of C ++ printf .

What is the C ++ equivalent for sprintf ?

+70
c ++ printf
Feb 13 '11 at 7:50
source share
7 answers

std::ostringstream

Example:

 #include <iostream> #include <sstream> // for ostringstream #include <string> int main() { std::string name = "nemo"; int age = 1000; std::ostringstream out; out << "name: " << name << ", age: " << age; std::cout << out.str() << '\n'; return 0; } 

Output:

 name: nemo, age: 1000 
+57
Feb 13 2018-11-11T00:
source share

Update, August 2019:

It looks like C ++ 20 will have std::format . The reference implementation is {fmt} . If you are looking for an alternative to printf() now, this will become a new β€œstandard” approach and is worth considering.

Original:

Use Boost.Format . It has printf -like syntax, type safety, std::string results, and many other interesting things. You will not return.

+24
Feb 13 2018-11-11T00:
source share

sprintf works fine in C ++.

+17
Feb 13 '11 at 8:27
source share

You can use the iomanip header file to format the output stream. Check out this one !

+7
Aug 04 '14 at 2:11
source share

Here's a nice feature for C ++ sprintf. Streams can become ugly if you use them too much.

 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(&str[0], size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) return str; if (n > -1) size = n + 1; else size *= 2; } } 

In C ++ 11 and later versions of std :: string, the use of continuous storage is guaranteed, which ends with '\0' , so it is legal to pass it to char * using &str[0] .

+5
Dec 02 '11 at
source share

Use a stream of strings to achieve the same effect. Alternatively, you can enable <cstdio> and use snprintf.

0
Feb 13 '11 at 7:52
source share

Depending on what you plan to use in sprintf() , std::to_string() may be useful and more idiomatic than other options:

 void say(const std::string& message) { // ... } int main() { say(std::to_string(5)); say("Which is to say " + std::to_string(5) + " words"); } 

The main advantage of std::to_string() , IMHO, is that it can be easily extended to support additional types that sprintf() cannot even dream of string types - something like the Java Object.toString() method.

0
Jul 31 '19 at 13:49
source share



All Articles