stringstream
作用1:分割字符串
作用2:更安全的类型转换
做一个对照:
操作 | string | 字符数组 |
定义字符串 | string s; | char s[100]; |
取得第i个字符 | s[i] | s[i] |
字符串长度 | s.length() 或 s.size() | strlen(s) |
读入一行 | getline(cin, s); | gets(s); |
赋值 | s = "you"; | strcpy(s, "you"); |
字符串连接 | s = s + "you"; s += "you"; | strcat(s, "you"); |
字符串比较 | s == "you" | strcmp(s, "you"); |
size_t pos = str.find("ssdf", 3);
//可以用if(pos == string::npos) 用来判断是否找到子串。
string str2 = str.substr(pos, 5);
//返回从pos开始的5长度子串
//如果不存在 pos位置超过字符串总长度 返回空串
//如果从pos开始并没有这么长的长度 就返回有效的 abc substr(0,100)== “abc”
stringstream
stringstream主要是用在將一个字符串分割,可以先用 .clear( ) 以及 .str( ) 將指定字串设定成一开始的內容,再用>>把个別的资料输出。
举个例子:
題目:输入的第一行有一个数字 N 代表接下來有 N 行资料,每一行资料里有不固定个数的整数(最多20个,每行最大200个字元),编程將每行的总和打印出來。
输入:
3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999
输出:
6
251
4995
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
//char kk[100] = "123 9 1";
string s;
stringstream ss;
int n;
cin >> n;
getline(cin, s); //读取换行
for (int i = 0; i < n; i++)
{
getline(cin, s);
ss.clear();//重置流的状态标志
ss.str(s);//成员函数 将字符串 导入 ss流中 char* string都可以
int sum = 0;
while (1)
{
int a;
ss >> a;
if(ss.fail())//比如ss流中有 1 23 156 当读完156后 再尝试读 流中已经没数字 就返回真
break;
sum += a;
}
cout << sum << endl;
}
return 0;
}
使用stringstream简化类型转换
以前用c
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
char a[100];
sprintf(a, "%d", 1000);//将右边的内容打印在字符串a中
printf("%s\n", a);
//输出字符串1000
int k;
sscanf(a, "%d", &k);//从字符串a中读取内容 写入k 确定 要控制好类型对应 而stringstream就不需要了
printf("%d\n", k);
//输出整型1000
sprintf(a, "%lf", 0.00001);
printf("%s\n", a); //可以
double k2;
sscanf(a, "%f", &k2);
printf("%f\n", k2);//乱码
return 0;
}
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
stringstream s;
long long k;
string a = "111111111111111111";
//s.str(a); 尽量不用这个吧 不用下面那句 用这句 下面的100不输出 不懂
s << a;//这样来给 插入到流
s >> k;
cout << k << endl;
int kk = 100;
s.clear();//对于一个流 若进行多次转换 记得clear()
//s.str(""); 尽量不用这个
s << kk;
string tmp;
s >> tmp;
cout << tmp << endl;
char f[100];//c字符串也可以
s.clear();
s << tmp;
s >> f;
cout << f <<endl;
return 0;
}
下面是运用模版 实现任意类型转换
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template<class T>
void to_string(string &result, const T &t)
{
ostringstream oss;
oss << t;
result = oss.str();
}
template<class out_type, class in_value>
out_type convert(const in_value & t)
{
stringstream stream;
stream << t;
out_type result;
stream >> result;
return result;
}
int main()
{
//to_string实例
string s1, s2, s3;
to_string(s1, 10.5); //double到string
to_string(s2, 123); //int到string
to_string(s3, true); //bool到string
cout << s1 << endl << s2 << endl << s3 << endl << endl;
//convert()例子
double d;
string salary;
string s = "12.56";
d = convert <double> (s); //d等于12.56
salary = convert <string> (9000.0); //salary等于"9000"
cout << d << endl << salary << endl;
return 0;
}