Yugenswitch
Yugenswitch

Reputation: 185

Why is std::stringstream not printing the correct numbers in this code?

So, very new to this. I am trying to change the input from the text file from string to double after I've grabbed it and put it into a vector. I want to perform mathematical operations with those numbers and some of the numbers are missing a digit or two after I've converted from string to double. (the file is converted from doc to txt because I cant figure out how to access doc files, if this is wrong please let me know). I would include the txt file in this question but I cant figure out how. so if that is necessary, please let me know how. Feel free to criticize the code, always willing to learn. I need it. :)

The numbers are in this exact format -> 0.00000 And some of them are coming out, after conversion, as 0.0000 or 0.000

int main() 
{
    std::string lines;
    std::vector <std::string> numbers{};
    std::vector <double> dbnumbers{};
    std::ifstream myfile("data.txt");

    while (myfile >> lines)
    {
        numbers.push_back(lines);
    }

    for (int i = 0; i < numbers.size(); ++i)
    {
        std::string tempstring;
        tempstring = numbers[i];
        std::stringstream tempd(tempstring);

        double line{};
        tempd >> line;
        dbnumbers.push_back(line);

    }
    for (auto element : numbers) std::cout << element << " / ";
    for (auto element2 : dbnumbers) std::cout << element2 << " / ";


    return 0;
}

Upvotes: 0

Views: 393

Answers (1)

rreignier
rreignier

Reputation: 31

It is difficult to tell without your input data but your std::cout might need std::setprecision to increase the number of digits to print.

Upvotes: 2

Related Questions