Stringstream库数据类型转换

基于sstream库的数据类型转换

定义了三个类:istringsteam,ostringsteam,stringstream分别用来进行流的输入输出和输入输出操作

基础用法:

1
2
3
4
5
int n;
string s='12345';
stringstream ss;
ss<<s;
ss>>n;//此时n=12345

使用stringstream提升效率

正常要给一个文件中写入内容

1
2
3
ofstream ofile("eg.text");
//每次符合条件时都会一行一行的往里面写入内容
ofile<<"xxxxx"<<endl;

使用stringstream往文件中写入内容,可以先把要输入的内容存储在对象的缓存区

1
2
3
4
ofstream ofile("eg.text");
stringstream oss;
oss<<"xxxx"<<endl;//每次满足条件时先写入缓存
ofile<<oss.str();//最后一次性写入

蓝桥杯题目

分析:例如里面的意思是:从一开始拼数字——1,2,3,4,5,6,7,8,9,10,11在11这里会用到第四个1,故按顺序拼只能拼到10,每次数字最先用完的是1,所以只需要统计1的使用频率,既可以算出可以拼到多少

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <sstream>
#include <algorithm>

using namespace std;
//将整型转化为字符串
string int_to_str(int i)
{
string output;
stringstream oss;
oss << i;
oss >> output;
return output;
}

int main()
{
int i = 1;
int count1 = 0;
while (1)
{
string s = int_to_str(i);
count1 += count(s.begin(), s.end(), '1');//调用algorithm头文件里的算法,计算1出现的次数
if (count1 >= 2021) { break; }
else { i += 1; }
}
if (count1 > 2021) { i -= 1; }//判断此时最大的i能不能被组成
cout << i << endl;
return 0;
}