打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C++学习——四种字符串与数据连接的方法

方法调用很简单,sprintf itoa函数在我的其他博客也有详解,请翻阅查看,话不多说,直接撸代码:

#include <iostream>#include <string>#include <cstdlib>#include <sstream>#include <cstring> using namespace std;//第一种C风格的转化(以前一直喜欢的  sprintf 功能强大)void test(){
    char *s = "dong";
    int a = 52;
    float b = .1314;
    char *buf = new char[strlen(s) + sizeof(a) + 1];
    sprintf(buf, "%s%d%.4f", s, a, b);
    printf("%s\n", buf);}//半C半C++风格void test1(){
    string s = "dong";
    int a = 520;
    char *buf = new char[10];//2147483647 int最大值
    _itoa(a, buf, 10);      //itoa虽然可以转化为各种进制,但是注意不能是float或者double
    cout << s + buf << " | ";
    _itoa(a, buf, 16);
    cout << s + buf << endl;}//纯C++风格void test2(){
    string s = "陈明东";
    int a = 52;
    double b = .1314;
    ostringstream oss;
    oss << s << a << b;
    cout << oss.str() << endl;}//C++11新特性void test3(){
    int a = 520;
    float b = 5.20;
    string str = "dong";
    string res = str + to_string(a);
    cout << res << endl;
    res = str + to_string(b);
    res.resize(8);
    cout << res << endl;}int main(){
    test();
    test1();
    test2();
    test3();
    return 0;}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
C语言itoa()函数和atoi()函数详解(整数转字符C实现)
c++string与数字之间的转换
string和stringstream用法总结
c++数字和字符串的转换
C/C++ 字符编码的转换(ut8、gb2312)
用C/C++代码检测ip能否ping通
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服