-1

I'm trying to take strings from vectors and convert them into doubles using stringstream. However, when I run this code:

  double tempDob;
  stringstream ss;
  ss << tempVec[3];
  ss >> tempDob;

I get weird stuff instead of a normal double. Here's an example: Original Strings(cout of tempVec[3]):

        15000000
62658722.54
91738635.67
        20
        29230756.5
        12

Converted doubles(cout of tempDob):

1.5e+07
6.26587e+07
9.17386e+07
2.92308e+07
4.70764e+07
3.53692e+07

How can I get these strings correctly converted to doubles through stringstream? Thanks!

2 Answers2

0

Like this:

istringstream is( somestring );
double d;
is >> d;

though of course your own code will have error handling.

  • And that does what actually? – πάντα ῥεῖ Dec 11 '16 at 22:56
  • Precision and how to do formatting is in question? – πάντα ῥεῖ Dec 11 '16 at 22:58
  • @πάντα ῥεῖ It converts the first space separated token in somestring to a double, if possible. –  Dec 11 '16 at 22:59
  • Thanks for the link to the other question,now I know it's giving me scientific notation. I tried fixing it using "fixed", but this still gave me scientific notation: – James Hall Dec 11 '16 at 23:30
  • stringstream ss; ss << fixed << tempVec[3]; double d; ss >> fixed >> d; – James Hall Dec 11 '16 at 23:30
  • @James The issue is not reading the double, from the string, as your question title implied, but formatting it once you have read it. So, once you have read d, you want something like cout << fixed << d; –  Dec 11 '16 at 23:37
  • @JamesHall A double doesn't contain info about formatting. So `ss >> fixed >> d` can't do anything useful. You simply read a normal double from the stream which is completely oblivious to scientific notation. The only way notation comes into play is when you format the double as a string again, such as during output via `cout`. – Felix Dombek Dec 11 '16 at 23:45
  • Thanks guys! I get it now – James Hall Dec 11 '16 at 23:54
0

You can use the same stringstream repeatedly like this:

std::vector<std::string> theVec { "        15000000",
                                  "62658722.54",
                                  "91738635.67",
                                  "        20",
                                  "        29230756.5",
                                  "        12" };
std::stringstream ss;
for (auto const& s : theVec)
{
    ss.clear();
    ss.str(s);
    double d;
    ss >> d;
    std::cout << d << "\n";
}
Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
  • Thanks, good to know. This time though I'm using it in a for loop with ss.clear() – James Hall Dec 11 '16 at 23:35
  • @JamesHall `ss.clear()` is necessary, I added it, but note that it does not clear the string but just the flags. This is different from `std::string::clear` etc. – Felix Dombek Dec 11 '16 at 23:39