0

I am trying to parse a string line which has comma separated values in and keep in the Vector. The challenge is that i m unable to retain the precision values after certain position. Below is the code which i am trying.

  string name = "1, 0, -23.5346 -412.13647, 0, 11.2, 0.4, -2233.12345, 0, 0, 0, 567.46436, 0, 0, 1.654321, 0.1232"


   stringstream ss(name);
    vector<string> result;
    int cc=0;

    while (ss.good ()) {
            string val;
            getline (ss, val, ',');
            cout <<"value for "<<cc<< " is "<<std::stod(val)<<endl;
            result.push_back(val);
            cout <<"cc "<< cc; 
            cc++;

    }    

The output i received is

value for 1 is 1
value for 2 is 0
value for 3 is -23.5346
value for 4 is -412.136
value for 5 is 0
value for 6 is 11.2
value for 7 is 0.4
value for 8 is -2233.12
value for 9 is 0
value for 10 is 0
value for 11 is 0
value for 12 is 567.464
value for 13 is 0
value for 14 is 0
value for 15 is 1.65432
value for 16 is 0.1232

In the above code, I am unable to retrain the precision values, for example instead of -412.13647, the value -412.136 is stored. How can i Resolve this issue?

DrunkenMaster
  • 1,218
  • 3
  • 14
  • 28
  • Does std::cout actually output the exact contents of the vector? – Michael Chourdakis May 15 '19 at 14:13
  • The code you show would not create the output you show. Please try to create a [mcve] to show us, together with the actual and expected output. – Some programmer dude May 15 '19 at 14:14
  • Also note that what you're doing with `while (ss.good()) { ...}` is almost equivalent to `while (!ss.eof()) { ... }` [which is almost always wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) (as is your condition). – Some programmer dude May 15 '19 at 14:15

2 Answers2

0

Your problem is that std::cout sets the precision.

Solution from this SO question using std::fixed.

double d = 3.14159265358979;
cout.precision(17);
cout << "Pi: " << fixed << d << endl;
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
0

Have you tried setprecision?

http://www.cplusplus.com/reference/iomanip/setprecision/

john
  • 373
  • 1
  • 16