2010年8月12日 星期四

高中 d098: Stringstream運用練習(C++)



想看題目請點我


#include <iostream>
#include <sstream>
using namespace std;

main() {
     string s1 ;
     while(getline(cin, s1))
     {
         string s2 ;
         int x = 0 , value = 0 , flag = 0 ;
         for(int i = 0 ; i <= s1.length() ; i++)
         {
             if((s1[i] == ' '|| s1[i] == '\0') && (flag==0))
             {
                 stringstream ss(s2); 
                 ss >> x;
                 value += x ;
                 //Init
                 s2 = "" ;
                 x = 0 ;
             }
             else if((s1[i] == ' '|| s1[i] == '\0') && (flag==1))
             {
                  flag = 0 ;
                  //Init
                  s2 = "" ;
             }
             else if(s1[i] >= '0' && s1[i] <= '9')
             {
                 s2 += s1[i];
             }
             else
             {
                 flag = 1 ;
             }
         }
         cout << value << endl ;
     }
}




這題剛好最近有做到類似的 ,
直接拿 d392 直接補強上線 ,
不懂的稍微看一下sstream 的用法就懂了^^