0

I'm searching for an efficient way to get a double out of a string in c++. I now the cstring to double function, however I can not use that because this string is the following format:

DOUBLE - SPACE - REST OF STRING THAT I ALSO NEED TO SAVE.

The problem is that the double can be of different sizes, so how can I get the double efficiently and that I am still able to save the rest of the string.

Benoit
  • 76,634
  • 23
  • 210
  • 236
Aesir
  • 3
  • 2

3 Answers3

4
std::istringstream s( theString );
s >> theDouble;

s now contains the rest of the string, which can easily be extracted.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
1

Use istringstream to read double value, ignore one character (space was expected), and read rest of line.

string s = "1.11 my string";

double d;
string rest;

istringstream iss(s);
iss >> d;
iss.ignore(); // ignore one character, space expected.
getline(iss, rest, '\0');
kamae
  • 1,825
  • 1
  • 16
  • 21
  • 1
    +1, but it's nice to see `if (iss >> d && iss.ignore() && getline(iss, rest)) ...; else std::cerr << "failed\n";` - too many beginning C++ programmers assume input succeeds and waste time understanding their mistakes.... – Tony Delroy Jul 18 '13 at 11:24
  • I copied this and it almost works, I however do now get the following error: main.cpp|31|error: variable ‘std::istringstream iss’ has initializer but incomplete type|. How can I solve this? – Aesir Jul 18 '13 at 11:30
  • 1
    @Aesir [Google](https://www.google.com/search?q=variable+istringstream+has+initializer+but+incomplete+type) -> [`#include `](http://stackoverflow.com/questions/8091976/using-istringstream-gives-error-why). – Bernhard Barker Jul 18 '13 at 11:33
  • @Aesir You are missing one include, most likely – Antonio Jul 18 '13 at 11:34
  • Ah I did include Istream, tnx. – Aesir Jul 18 '13 at 11:35
0

If you have a fixed format for your input. You can, first split it with space. Then you have following:

DOUBLE
REST OF STRING THAT I ALSO NEED TO SAVE.

Split:

std::string str = "3.66 somestring";
std::stringstream ss(str);
std::string buffer;
while(std::getline(ss, buffer, ' ')) {
  // add necessary data to containers...
}

Now you can use std::atof to parse your double.

edit: Added split code:

Cengiz Kandemir
  • 375
  • 1
  • 4
  • 16