河北大学暑期程序设计训练每日知识分享-day10

每日分享——C++11特性中的to_string

to_string的的头文件是#include <string>,to_string最常⽤的就是把⼀个int 型变量或者double型变量转化为 string 类型的变量,当然也可以转 doublefloat 等类型的变量,这在很多PAT字符串处理的题目中很有用处,以下是示例代码

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = to_string(123); // 将123这个数字转换为字符串
cout << s1 << endl;
string s2 = to_string(4.5); // 将4.5这个数字转换为字符串
cout << s2 << endl;
cout << s1+s2 << endl; // 将s1和s2两个字符串转换为字符串拼接起来并输出
printf("%s\n", (s1+s2).c_str()); // 如果想用printf输出字符串需要加一个.c_str()
return 0;
}

除此之外,还可以使用stoistod将字符串string转化为对应的intdouble型变量,对于一些字符串处理的题非常有帮助,示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "123";
int a = stoi(str);
cout << a << endl;
str = "123.44";
double b = stod(str);
cout << b << endl;
return 0;
}

不仅有stoistod两种,相应的还有:

stof (string to float)

stold(string to long double)

stol(string to long)

stoll(string to long long)

stoul(string to unsigned long)

stoull (string to unsigned long long