stringstream 的用法就见代码吧:
1 ///string 转 int 2 int main() 3 { 4 string a="10"; 5 stringstream ss; 6 int n; 7 ss<<a; 8 ss>>n; 9 n+=5; 10 printf("%d\n",n); 11 return 0; 12 }
1 ///int 转 string 2 int main() 3 { 4 int n=120; 5 stringstream ss; 6 ss<<n; 7 string a; 8 ss>>a; 9 a+="123"; 10 cout<<a<<endl; 11 return 0; 12 }
1 ///string 转 int + 分离数 2 int main() 3 { 4 string a; 5 getline(cin,a); 6 stringstream ss; 7 ss<<a; 8 int n; 9 while( ss>>n ){ 10 cout<<n<<endl; 11 } 12 return 0; 13 }
1 ///用于单词分割 2 int main() 3 { 4 string a; 5 getline(cin,a); 6 stringstream ss; 7 ss<<a; 8 string word; 9 while( ss>>word ){ 10 cout<<word<<endl; 11 } 12 return 0; 13 }
1 ///string 转 double 2 int main() 3 { 4 string result="1000.123"; 5 double n; 6 stringstream stream; 7 stream<<result; 8 stream>>n; 9 printf("%.6f\n",n); 10 return 0; 11 }
1 int main() 2 { 3 string a; 4 stringstream ss; 5 while( getline(cin,a)){ 6 ss.clear();///清空其状态 7 ss.str(""); ///清空其内容 8 ss<<a; 9 string word; 10 while( ss>>word ){ 11 printf("%s\n",word.c_str()); 12 } 13 } 14 return 0; 15 }
原文地址:https://www.cnblogs.com/wsy107316/p/12255117.html
时间: 2024-10-27 02:50:49