~ubuntu-branches/ubuntu/trusty/ticcutils/trusty-proposed

« back to all changes in this revision

Viewing changes to include/ticcutils/StringOps.h

  • Committer: Package Import Robot
  • Author(s): Ko van der Sloot
  • Date: 2013-04-18 15:14:58 UTC
  • mfrom: (1.1.2)
  • Revision ID: package-import@ubuntu.com-20130418151458-o3zeb8f0676003y3
Tags: 0.4-3
debian/control: also added Replaces: libticcutils1-dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*
2
 
  $Id: StringOps.h 15107 2012-08-13 08:34:34Z sloot $
 
2
  $Id: StringOps.h 15844 2013-03-28 17:40:24Z sloot $
3
3
  $URL: https://ilk.uvt.nl/svn/sources/libticcutils/trunk/include/ticcutils/StringOps.h $
4
4
 
5
 
  Copyright (c) 1998 - 2012
 
5
  Copyright (c) 1998 - 2013
6
6
  ILK   - Tilburg University
7
7
  CLiPS - University of Antwerp
8
8
 
32
32
 
33
33
#include <string>
34
34
#include <vector>
 
35
#include <sstream>
 
36
#include <stdexcept>
35
37
 
36
38
namespace TiCC {
37
39
  std::string trim( const std::string&, const std::string& = " \t\r\n" );
52
54
  }
53
55
  
54
56
  std::string format_nonascii( const std::string& );
 
57
 
 
58
  template< typename T >
 
59
    T stringTo( const std::string& str ) {
 
60
    T result;
 
61
    std::stringstream dummy ( str );
 
62
    if ( !( dummy >> result ) ) {
 
63
      throw( std::runtime_error( "conversion from string '"
 
64
                                 + str + "' failed" ) );
 
65
    }
 
66
    return result;
 
67
  }
 
68
  
 
69
  template<>
 
70
    inline bool stringTo<bool>( const std::string& str ) { 
 
71
    std::string b = TiCC::uppercase( str );
 
72
    if ( b == "YES" || b == "TRUE" || b == "1" ) 
 
73
      return true; 
 
74
    else if ( b == "FALSE" || b == "NO" || b == "0" ) 
 
75
      return false; 
 
76
    else
 
77
      throw( std::runtime_error( "conversion from string '" 
 
78
                                 + str + "' to bool failed" ) ); 
 
79
  } 
 
80
  
 
81
  template< typename T >
 
82
    bool stringTo( const std::string& str, T& result ) {
 
83
    try {
 
84
      result = stringTo<T>( str );
 
85
      return true;
 
86
    }
 
87
    catch( ... ){
 
88
     return false;
 
89
    }
 
90
  }
 
91
 
 
92
  template <typename T>
 
93
    bool stringTo( const std::string& s, T &answer, T low, T upp ){
 
94
    try {
 
95
      T tmp = stringTo<T>( s );
 
96
      if ( (tmp >= low) && (tmp <= upp) ){
 
97
        answer = tmp;
 
98
        return true;
 
99
      }
 
100
      return false;
 
101
    }
 
102
    catch(...){
 
103
      return false;
 
104
    }
 
105
  }
 
106
  
 
107
  template< typename T >
 
108
    std::string toString ( const T& obj, bool=false ) {
 
109
    std::stringstream dummy;
 
110
    if ( !( dummy << obj ) ) {
 
111
      throw( std::runtime_error( "conversion to long string failed" ) );
 
112
    }
 
113
   return dummy.str();
 
114
  }
55
115
  
56
116
}
57
117