0

I am writing a program to read a text file, do some calculations and output into another text file. The program runs fine but the problem I am having is that the numbers that are written to the text file aren't precise enough. They only go to 2 decimal points and I need the to go to at least 3. Here is the code where I convert the vector<long double> new_times into a string so I can write it to the text file:

//Convert vector to string
vector<string> tempStr;
for (unsigned int i(0); i < new_times.size(); ++i){
    ostringstream doubleStr;
    doubleStr << new_times[i];    
    tempStr.push_back(doubleStr.str());
}

//Write new vector to a new times file
ofstream output_file("C:/Users/jmh/Desktop/example.txt");
ostream_iterator<string> output_iterator(output_file, "\n");
copy(tempStr.begin(), tempStr.end(), output_iterator);

I know that the vector has a higher precision than 2 decimal places because when I used the setprecision() function in a cout line the output was fine:

cout << setprecision(12) << new_times[3] << endl;
output: 7869.27189716

Can I use the setprecision() function somehow when I am writing to the text file? Or Do I need to do something else? Any help would be appreciated.

oodan123
  • 459
  • 2
  • 8
  • 23
  • c++ iostreams: The idea is better than the implementation. While this will draw much hate: Don't use iostream and you are usually better off (faster done). – BitTickler Sep 11 '15 at 06:03

1 Answers1

2

Can I use the setprecision() function somehow when I am writing to the text file?

Yes, but you've to use it on the ostringstream you're using to print the long double to a string.

ostringstream doubleStr;
doubleStr << std::fixed << std::setprecision(12);
doubleStr << new_times[i];

would print the number with 12 decimal digits of precision, past the decimal point. std::fixed is to make sure that the number is printed in fixed format; see the documentation for details.

I'd recommend setting the precision to numeric_limits<long double>::max_digits10 to avoid loss of precision during the double → text → double round-trip. See What is the purpose of max_digits10 and how is it different from digits10? for details.

Live example.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222