c++字符串拼接

C++ 字符串拼接

#include <iostream>
#include <sstream>
#include <istream>
#include <iomanip>

// 几种字符串拼接和 cout 格式化输出

// 使用流的方式拼接,需要包含头文件 sstream
void test01(){
	std::string s1 = "my name is ";
    int age = 23;
    std::string s2 = ", and my height is ";
    double height = 168.5;
    std::ostringstream os;
    os << s1 << age << s2 << height;
    std::cout << os.str() << std::endl;
}

// 使用 append() 的方式拼接
void test02(){
    std::string s1 = "my name is ";
    int age = 23;
    std::string s2 = ", and my height is ";
    double height = 168.5;
    s1.append(std::to_string(age));
    s1.append(s2);
    s1.append(std::to_string(height));
    std::cout << s1 << std::endl;
}

// 使用 + 号进行拼接(使用 to_string() 函数)
void test03(){
    std::string s1 = "my name is ";
    int age = 23;
    std::string s2 = ", and my height is ";
    double height = 168.5;
    std::string s = s1 + std::to_string(age) + s2 + std::to_string(height);
    std::cout << s << std::endl;
}

void test04(){
    std::string s1 = "my name is ";
    int age = 23;
    std::string s2 = ", and my height is ";
    double height = 168.5;
    printf("%s%d%s%.2f\n", s1.c_str(), age, s2.c_str(), height);
}

// 字符串转 int、double,需要包含头文件 iomanip 和 istream
void test05(){
    int a = atoi("8");
    double b = atof("3.14");
    int c;
    int d = std::stoi("123");
    double e = std::stof("6.28");
    std::cout << a << "\t" << b << std::endl;
    // 使用流的方式
    std::istringstream is("66");
    is >> c;
    std::cout << c << "\t" << d << "\t" << e << std::endl;
}

// cout 格式化输出
void test06(){
    std::cout << std::hex << 256 << std::endl;       // 以十六进制输出整数
    std::cout << std::oct << 256 << std::endl;       // 以八进制输出整数
    std::cout << std::fixed << 3.1415926 << std::endl;  // 以普通小数输出浮点数
    std::cout << std::scientific << 3.1415926 << std::endl;   // 以科学计数法输出浮点数
    std::cout << std::setbase(16) << 256 << std::endl;   // 设置输出整数的进制
    std::cout << std::setbase(8) << 256 << std::endl;   // 设置输出整数的进制
    std::cout << std::setbase(10);
    std::cout << std::setw(12) << "12345678" << std::endl;  // 指定输出宽度为 w 个字符,或输人字符串时读入 w 个字符
    /*
        设置输出浮点数的精度为 n。 
        在使用非 fixed 且非 scientific 方式输出的情况下,n 即为有效数字最多的位数,
        如果有效数字位数超过 n,则小数部分四舍五人,或自动变为科学计数法输出并保留一共 n 位有效数字。 
        在使用 fixed 方式和 scientific 方式输出的情况下,n 是小数点后面应保留的位数。
    */
    std::cout << std::setprecision(5) << 1234.5678 << std::endl;
}

int main(){
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();
    return 0;
}

输出结果如下:

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

後物

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值