Advertisement
Nbrevu

Tuenti Contest 1 (Pablo Moreno)

Jun 20th, 2011
1,767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. /*
  2.     Author: Pablo Moreno Olalla
  3.     Email address: darthbrevu@yahoo.es
  4. */
  5. #include "BigNumber.h"
  6.  
  7. #include <list>
  8. #include <cstdio>
  9. #include <string>
  10. #include <iostream>
  11. #include <algorithm>
  12.  
  13. using namespace std;
  14.  
  15. //These functions are going to be called just at one point in the code.
  16. //So there's no loss in inlining them, although they aren't very small.
  17. inline void tokenize(const string &str,list<string> &out,char chr=' ')  {
  18.     //This could alse have been achieved using objects from the sstream header, but this is safer.
  19.     string::size_type pos=0;
  20.     string::size_type pos2;
  21.     size_t N=str.length();
  22.     while (pos<N&&pos!=string::npos)    {
  23.         pos=str.find_first_not_of(chr,pos);
  24.         if (pos==string::npos) break;
  25.         pos2=str.find_first_of(chr,pos);
  26.         out.push_back(str.substr(pos,pos2-pos));
  27.         pos=pos2;
  28.     }
  29. }
  30.  
  31. inline void funString(const string &str)    {
  32.     //This function reads a line and adds the numbers contained there, and then shows the result.
  33.     list<string> substrs;
  34.     tokenize(str,substrs);
  35.     Number res=0;
  36.     bool anyNumber=false;
  37.     for (list<string>::const_iterator it=substrs.begin();it!=substrs.end();++it) try    {
  38.         res+=Number(*it);   //This may raise an exception if the string pointed by it does not contain a number.
  39.         anyNumber=true;
  40.     }   catch (const runtime_error &)   {}  //Not a number? Well... let's just ignore it and continue adding ;).
  41.     if (anyNumber) cout<<static_cast<string>(res)<<endl;    //No numbers? Then let's just not show anything.
  42. }
  43.  
  44. int main(int argc,char **argv)  {
  45.     //The first two lines are not strictly necessary, but make the code a little more handy.
  46.     if (argc>=2) freopen(argv[1],"r",stdin);
  47.     if (argc>=3) freopen(argv[2],"w",stdout);
  48.     string tmp;
  49.     do  {
  50.         getline(cin,tmp);
  51.         funString(tmp);
  52.     }   while (!cin.eof());
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement