初探stringstream

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 }

 

posted @ 2020-02-03 12:11  swsyya  阅读(141)  评论(0编辑  收藏  举报

回到顶部