Changeset 1005


Ignore:
Timestamp:
Jan 24, 2008, 5:26:08 PM (14 years ago)
Author:
Peter
Message:

adding conversion function - from string to numerical type

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/yat/utility/utility.h

    r1000 r1005  
    3434
    3535#include <string>
     36#include <stdexcept>
     37#include <sstream>
    3638#include <utility>
    3739#include <vector>
     
    4244
    4345  class vector;
     46
     47  /**
     48     \brief convert string to (numerical) type
     49
     50     \throw runtime_error if conversion fails
     51   */
     52  template<typename T>
     53  T convert(const std::string& s)
     54  {
     55    std::stringstream ss(s);
     56    T a;
     57    ss >> a;
     58    bool ok = true;
     59    if(ss.fail())
     60      ok = false;
     61    // Check that nothing is left on stream
     62    std::string b;
     63    ss >> b;
     64    if (!b.empty() || !ok)
     65      throw std::runtime_error(std::string("convert(\"")+s+std::string("\")"));
     66    return a;
     67  }
    4468
    4569  ///
Note: See TracChangeset for help on using the changeset viewer.