1

I am trying to read this csv file, let's call it "file.csv", and I'm trying to put it into a vector of double.

This csv contains numbers like:

755673.8431514322,
684085.6737614165,
76023.8121728658, 
...

I tried using stringstream, and it successfully input these number to the vector but the input numbers is not like I wanted. Instead, the inputted numbers are

7556373, 684085, 76023.8

How can I read the whole digits without throwing any of it away?

This is my code

vector<long double> mainVector;

int main() 
{
    ifstream data;
    data.open("file.csv");
    while (data.good()) 
    {
        string line;
        stringstream s;
        long double db;
        getline(data, line, ',');
        s << line;
        s >> db;
        mainVector.push_back(db);
    }
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 3
    Are you absolutely certain this isn't because of how you are printing the numbers out? Give [How do I print a double value with full precision using cout?](https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) a read. – user4581301 Nov 04 '18 at 16:27
  • @user4581301 im not certain, im actually clueless about this, but thanks for the reference, i will read it – normal user Nov 05 '18 at 03:12

1 Answers1

2

How to read the whole digits without throwing any of it.

As @user4581301 mentioned in the comments, I guess you are missing std::setprecision() while outputting.

However, you do not need std::stringstream to do the job. Convert line(which is a string directly to double using std::stold and place into the vector directly as follows.

That being said, use of std::stold will make sure not to have wrong input to the vector, by throwing std::invalid_argument exception, if the conversion from string to double was unsuccessful. (Credits to @user4581301)

#include <iostream>
#include <fstream>
#include <vector>  // std::vector
#include <string>  // std:: stold
#include <iomanip> // std::setprecision

int main()
{
    std::vector<long double> mainVector;
    std::ifstream  data("file.csv");
    if(data.is_open())
    {
        std::string line;
        while(std::getline(data, line, ','))
            mainVector.emplace_back(std::stold(line));
    }
    for(const auto ele: mainVector)
        std::cout << std::setprecision(16) << ele << std::endl;
                    // ^^^^^^^^^^^^^^^^^^^^ 
    return 0;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 1
    @JeJo thank you so much, it worked. I thought the problem was on how the numbers inputted to the variable but the problem only on printing the numbers – normal user Nov 05 '18 at 03:12