不用第三方库
时间: 2023-06-30 22:24:49 浏览: 43
如果不使用第三方库,可以自己实现一个简单的 `format` 函数。下面是一个示例实现:
```c++
#include <string>
#include <sstream>
#include <iostream>
template<typename... Args>
std::string format(const std::string& fmt, Args... args) {
size_t len = std::snprintf(nullptr, 0, fmt.c_str(), args...);
std::vector<char> buf(len + 1);
std::snprintf(&buf[0], len + 1, fmt.c_str(), args...);
return std::string(&buf[0], &buf[0] + len);
}
int main() {
std::string name = "John";
int age = 25;
float height = 1.75;
std::string result = format("My name is %s, I'm %d years old and %.2fm tall.", name.c_str(), age, height);
std::cout << result << std::endl;
return 0;
}
```
在这个实现中,我们使用了 C++11 的可变参数模板来支持不同类型的参数。然后使用 `std::snprintf` 函数来将格式化后的字符串写入到缓冲区中,最后将缓冲区中的字符串转换成 `std::string` 类型并返回。
需要注意的是,在使用 `std::snprintf` 函数时,需要先计算需要的缓冲区大小并分配好缓冲区,再将格式化后的字符串写入到缓冲区中。