多类型拼接成string,类型转换
多类型拼接成string
拼接风格
#include <iostream>
#include <string>
#include <sstream>
using std::cin;
using std::cout;
using std::endl;
//C风格
void testC() {
char a[] = "hello";
int b = 10;
double c = 6.6;
char buf[100] = {0};
sprintf(buf, "%s%d%lf", a, b, c);
printf("%s\n", buf);
}
//Cpp风格
void testCpp() {
char a[] = "hello";
int b = 10;
double c = 6.6;
std::ostringstream out;
out << a << b << c;
cout << out.str() << endl;
}
//Cpp11风格
void testCpp11() {
char a[] = "hello";
int b = 10;
double c = 6.6;
std::string res = a + std::to_string(b) + std::to_string(c);
cout << res << endl;
}
int main() {
testC(); //hello106.600000
testCpp(); //hello106.6
testCpp11(); //hello106.600000
return 0;
}
C++类型转换函数
int转换成string
c++11标准增加了全局函数std::to_string,包括九种重载实现:
- string to_string (int val);
- string to_string (long val);
- string to_string (long long val);
- string to_string (unsigned val);
- string to_string (unsigned long val);
- string to_string (unsigned long long val);
- string to_string (float val);
- string to_string (double val);
- string to_string (long double val);
string转换成int
标准库函数:
整形:
atoi()
浮点型:
atof()
长整型:
atol()
Example:
std::string str = "123";
int n = atoi(str.c_str());
cout<<n; //123
借助字符串流转换
标准库定义了三种类型字符串流(在sstream头文件):
istringstream
:输入字符串流ostringstream
:输出字符串流stringstream
:字符串流,可输入输出
除了从iostream继承来的操作
- sstream类型定义了一个有string形参的构造函数
- stringstream stream(s):创建了存储s副本的stringstream对象,s为string类型对象
- 定义了名为str的成员,用来读取或设置stringstream对象所操纵的string值:
- stream.str():返回stream中存储的string类型对象
- stream.str(s):将string类型的s复制给stream,返回void
Example:
int aa = 30;
stringstream ss;
ss<<aa;
string s1 = ss.str();
cout << s1 << endl; // 30
istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
int i;
is >> i; //从is流中读入一个int整数存入i中