学堂 学堂 学堂公众号手机端

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

lewis 1年前 (2024-02-02) 阅读数 3 #技术

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

使用std::stringstream

#include<iostream> #include<sstream> intmain(){ std::stringstreamss; intnum=10; floatf=3.14; std::stringstr="Hello"; ss<<"Number:"<<num<<",Float:"<<f<<",String:"<<str; std::stringformatted_str=ss.str(); std::cout<<formatted_str<<std::endl; return0; }

使用printf函数:


#include<iostream> #include<cstdio> intmain(){ intnum=10; floatf=3.14; std::stringstr="Hello"; charbuffer[100]; std::sprintf(buffer,"Number:%d,Float:%.2f,String:%s",num,f,str.c_str()); std::stringformatted_str=buffer; std::cout<<formatted_str<<std::endl; return0; }

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

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门