可以格式化吗std::string
传递一组参数?
目前我正在以这种方式格式化字符串:
string helloString = "Hello %s and %s";
vector<string> tokens; //initialized vector of strings
const char* helloStringArr = helloString.c_str();
char output[1000];
sprintf_s(output, 1000, helloStringArr, tokens.at(0).c_str(), tokens.at(1).c_str());
但向量的大小是在运行时确定的。有没有类似的功能sprintf_s
它接受参数集合并格式化 std::string/char*?我的开发环境是 MS Visual C++ 2010 Express。
EDIT:我想实现类似的目标:
sprintf_s(output, 1000, helloStringArr, tokens);
实现类似 sprintf 功能的最 C++ 风格的方法是使用字符串流 http://www.cplusplus.com/reference/iostream/stringstream/.
这是一个基于您的代码的示例:
#include <sstream>
// ...
std::stringstream ss;
std::vector<std::string> tokens;
ss << "Hello " << tokens.at(0) << " and " << tokens.at(1);
std::cout << ss.str() << std::endl;
非常方便,不是吗?
当然,您可以充分利用 IOStream 操作来替换各种 sprintf 标志,请参阅此处http://www.fredosaurus.com/notes-cpp/io/omanipulators.html http://www.fredosaurus.com/notes-cpp/io/omanipulators.html以供参考。
一个更完整的例子:
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
int main() {
std::stringstream s;
s << "coucou " << std::setw(12) << 21 << " test";
std::cout << s.str() << std::endl;
return 0;
}
打印:
coucou 21 test
Edit:
正如OP所指出的,这种做事方式不允许使用可变参数,因为没有预先构建的“模板”字符串允许流迭代向量并根据占位符插入数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)