stringstream用法

 1、字符串分割

 1 int main() {
 2     string s = "asdhj,sfkkjdsi,sdni";
 3     istringstream ss(s);
 4     string temp;
 5     while (getline(ss, temp, ','))
 6         cout << temp << endl;
 7     string t = "a5151,sf79dsi,sd120i";
 8     ss.clear();
 9     ss.str(t);
10     while (getline(ss, temp, ','))
11         cout << temp << endl;
12     system("pause");
13     return 0;
14 }

2、类型转换

 1 int main() {
 2     string s = "123";
 3     istringstream iss(s);
 4     int i;
 5     iss >> i;
 6     cout << i << endl;
 7     s = "12.345";
 8     iss.clear();
 9     iss.str(s);
10     float f;
11     iss >> f;
12     cout << f << endl;
13     system("pause");
14     return 0;
15 }

stringstream类型转换的时候,一直读到第一个不符合类型的字符为止。

 1 int main() {
 2     string s = "123.456";
 3     istringstream iss(s);
 4     int i;
 5     iss >> i;
 6     cout << i << endl;
 7     float f;
 8     iss >> f;
 9     cout << f << endl;
10     system("pause");
11     return 0;
12 }

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

demo:利用stringstream实现字符串数字计算

 1 #include<iostream>
 2 #include<sstream>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     string s1 = "-123.45";
 8     double f1;
 9     string s2 = "123.456";
10     double f2;
11     istringstream is1(s1);
12     is1 >> f1;
13     cout << f1 << endl;
14     istringstream is2(s2);
15     is2 >> f2;
16     cout << f2 << endl;
17     double f = f1 + f2;
18     stringstream os;
19     os << f;
20     string s;
21     os >> s;
22     cout << s << endl;
23         return 0;
24 }

 

转载于:https://www.cnblogs.com/Zzz-y/p/9015873.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值