[英]How to use conversion specifier character in C++?
In Python I can do this: 在Python中,我可以这样做:
print("Hello, %s!" % username)
How do I in C++ do the similar thing? 我如何在C ++中做类似的事情? I can do this, but it's probably not a good practice:
我可以这样做,但这可能不是一个好习惯:
void welcome_message(std::string username) {
std::cout << "Hello, " << username << "!" <<std::endl;
}
For simple code, you may use std::cout
. 对于简单的代码,您可以使用
std::cout
。 But this is not very good for localisation and looks kind of ugly. 但这对本地化不是很好,而且看起来很丑。
Boost.Format fixes this by providing functionality very similar to that old Python 2 string formatting feature you demonstrate in your question (which was superseded by str.format()
). Boost.Format通过提供与您在问题中演示的旧Python 2字符串格式化功能非常相似的功能(已被
str.format()
取代)来str.format()
此问题。 It's a little like C's printf
, except safe. 除了安全,它有点像C的
printf
。
Here's an example: 这是一个例子:
#include <string>
#include <iostream>
#include <boost/format.hpp>
void welcome_message(const std::string& username)
{
std::cout << boost::format("Hello, %s!\n") % username;
}
int main()
{
welcome_message("Jim");
}
void welcome_message(const std::string& username) {
std::cout << "Hello, " << username << "!" <<std::endl;
}
is an extremely good thing to do in C++ unless you're doing something particularly performance-critical. 除非您正在做一些对性能至关重要的事情,否则在C ++中做一件非常好的事情。 Relying on the heavily overloaded
<<
for std::ostream
is good practice. 对
std::ostream
依赖严重过载的<<
是一个好习惯。 It's what it's there for. 这就是它的用途。
Note I've changed the function prototype to avoid an unnecessary string copy. 注意我已经更改了函数原型,以避免不必要的字符串复制。 The
printf
way is littered with dangerous corner-cases: you need to get the formatters exactly correct else you risk the behaviour of your program being undefined. printf
方法到处都是危险的极端情况:您需要使格式化程序完全正确,否则您就有可能不确定程序的行为。
The only criticism I can levy on this is your use of std::endl
. 我对此唯一的批评是您对
std::endl
。 Use "!\\n"
instead. 使用
"!\\n"
代替。
You can always C's printf: 您可以随时使用C的printf:
#include <cstdio>
void welcome_message(const std::string &username) {
printf("Hello, %s\n", username.c_str());
}
Notice, though, that you have to convert username
to a C string using c_str()
. 但是请注意,您必须使用
c_str()
将username
转换为C字符串。
As mentioned, using cout
and <<
is pretty standard, but many people argue against it for many reasons (eg: iternationalization, readability). 如前所述,使用
cout
和<<
是相当标准的,但是许多人反对它的原因很多(例如:迭代化,可读性)。 So, if you prefer string formatting, there's your option. 因此,如果您喜欢字符串格式,则可以选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.