2
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {

    istringstream iss("2.832 1.3067d nana 1.678");
    double num = 0;
    while(iss >> num || !iss.eof()) {
        if(iss.fail()) {
            iss.clear();
            string dummy;
            iss >> dummy;
            continue;
        }
        cout << num << endl;
    }
    return 0;
}

Using stringstream to print number but when i included, for example 1.3067d, but it still print 1.3067. How can i print the number only? I want it to print 2.832 and 1.678 only.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
  • 1
    Read as strings, then convert to number using [`std::stod`](http://en.cppreference.com/w/cpp/string/basic_string/stof). Then you can detect errors in the input like yours. – Some programmer dude Nov 07 '16 at 11:22

1 Answers1

0

If you use the stream extraction operator to pull a double out of a stream, the stream will read as much as it can that it can interpret as a double and stop when it reaches some data that it can't incorporate. In your case, if you try to read 1.3067d as a double, the stream will successfully read 1.3067 as a double and leave the d behind to be read by the next operation.

Since you have space-separated tokens in your string, one way to address this is to read each token as a string, then, having done so, see whether the token you pulled out can be converted to a double without error. Here's one way to do this:

for (string token; iss >> token; ) {
    istringstream converter(token);
    double value;

   if (converter >> value) {
       char leftover;
       if (!(converter >> leftover)) {
           /* Successfully read a double with no remaining garbage! */
           cout << value << endl;
       }
    }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065