c++怎么格式化字符串

   2024-11-04 2630
核心提示:在C++中,可以使用std::stringstream或者printf函数来格式化字符串。使用std::stringstream:#include iostream#include sstream

在C++中,可以使用std::stringstream或者printf函数来格式化字符串。

使用std::stringstream

#include <iostream>#include <sstream>int main() {    std::stringstream ss;    int num = 10;    float f = 3.14;    std::string str = "Hello";    ss << "Number: " << num << ", Float: " << f << ", String: " << str;    std::string formatted_str = ss.str();    std::cout << formatted_str << std::endl;    return 0;}

使用printf函数:

#include <iostream>#include <cstdio>int main() {    int num = 10;    float f = 3.14;    std::string str = "Hello";    char buffer[100];    std::sprintf(buffer, "Number: %d, Float: %.2f, String: %s", num, f, str.c_str());    std::string formatted_str = buffer;    std::cout << formatted_str << std::endl;    return 0;}

这样就可以通过std::stringstream或者printf函数来格式化字符串。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号