0

Possible Duplicate:
How can I convert string to double in C++?

how can I cast string to double in c++?

I have a string vector with numbers in it and i want to copy it into a vector of type double

while (cin >> sample_string)
    {
        vector_string.push_back(sample_string);
    }

    for(int i = 0; i <= vector_string.size(); i++)
    {
        if(i != 0 && i != 2 && i != vector_string.size()-1)
            vector_double.push_back((double)vector_string[i]);
    }

edit: i cant use BOOST

Community
  • 1
  • 1
124697
  • 22,097
  • 68
  • 188
  • 315

3 Answers3

5

I think you should use the stringstream class provided with the STL. It enables you to convert from string to double and the other way around. Something like this should work:

#include <sstream>
string val = "156.99";
stringstream s;
double d = 0;
s << val;
s >> d;
The Coding Monk
  • 7,684
  • 12
  • 41
  • 56
2

Assuming you have boost installed,

{
  using boost::lexical_cast;
  vector_double.push_back(lexical_cast<double>(vector_string[i]));
}

Assuming you don't have boost installed, add this function template, and invoke it:

template <class T1, class T2>
T1 lexical_cast(const T2& t2)
{
  std::stringstream s;
  s << t2;
  T1 t1;
  if(s >> t1 && s.eof()) {
    // it worked, return result
    return t1;
  } else {
    // It failed, do something else:
    // maybe throw an exception:
    throw std::runtime_error("bad conversion");
    // maybe return zero:
    return T1();
    // maybe do something drastic:
    exit(1);
  }
}

int main() {
  double d = lexical_cast<double>("1.234");
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

Boost (among others) provides a lexical_cast for exactly your purpose.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111