stringstream用法
Posted Zzz...y
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于stringstream用法的主要内容,如果未能解决你的问题,请参考以下文章