C++ 相当于 sprintf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4983092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ equivalent of sprintf?
提问by lital maatuk
I know that std::coutis the C++ equivalent of printf.
我知道这std::cout是 C++ 等价的printf.
What is the C++ equivalent of sprintf?
什么是 C++ 等价物sprintf?
采纳答案by Vijay Mathew
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
回答by janm
Update, August 2019:
2019 年 8 月更新:
It looks like C++20 will have std::format. The reference implementation is {fmt}. If you are looking for a printf()alternative now, this will become the new "standard" approach and is worth considering.
看起来 C++20 将有std::format. 参考实现是{fmt}。如果您现在正在寻找printf()替代方案,这将成为新的“标准”方法,值得考虑。
Original:
原来的:
Use Boost.Format. It has printf-like syntax, type safety, std::stringresults, and lots of other nifty stuff. You won't go back.
使用Boost.Format。它具有printf类似语法、类型安全、std::string结果和许多其他漂亮的东西。你不会回去。
回答by vinkris
回答by Erik Aronesty
Here's a nice function for a c++ sprintf. Streams can get ugly if you use them too heavily.
这是一个很好的 c++ sprintf 函数。如果您过多地使用流,流会变得丑陋。
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, std::string is guaranteed to use contiguous storage that ends with '\0', so it is legal to cast it to char *using &str[0].
在 C++11 及更高版本中,std::string 保证使用以 结尾的连续存储'\0',因此将其强制转换为char *using是合法的&str[0]。
回答by regality
Use a stringstream to achieve the same effect. Also, you can include <cstdio>and still use snprintf.
使用 stringstream 来实现相同的效果。此外,您可以包含<cstdio>并仍然使用 snprintf。
回答by Guss
Depending on what exactly you plan on sprintf()ing, std::to_string()might be useful and more idiomatic than other options:
根据您的确切计划sprintf(),std::to_string()可能比其他选项有用且更惯用:
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 extended easily to support additional types that sprintf()can't even dream of stringifying - kind of like Java's Object.toString()method.
std::to_string()恕我直言,它的主要优点是它可以轻松扩展以支持其他类型,这些类型sprintf()甚至连字符串化都做不到——有点像 Java 的Object.toString()方法。

