简体   繁体   中英

Using sprintf without a buffer variable

Is there a way to use sprintf() without a predefined variable?

Instead of:

char buffer[80];
sprintf(buffer, "%d",i );
myfunc(buffer);

I'd like to use:

myfunc(stringformat("%d",i));

Writing C++ , mean C-like functions without OOP.

Do you necessarily need to use same formatting rules as in printf/sprintf ? If so there is no standard library function to do that and you'll need to probably write your own using snprint under the hood (in edge cases for large format strings you would probably need to iterate over increasingly large buffer sizes or just limit maximum supported size of the output).

If you need something similar, but with different formatting - earliest it appears in standard library is C++20: std::format . There are also alternatives to standard library eg boost::format , folly::sformat .

Also in many cases using stringstream is more convenient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM