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;
}
输出结果如下: