You can't have your cake and eat it too! :)
I mean, you want the exact representation of a string in a number, without having to pay the cost in terms of memory (by just storing the string*).
So in that case the best thing you could do is to use a long double
, you know the L
we append at the end of numeric constants. However, of course this also has its limits (..since our computer also has limits). Moreover, what a waste of space (and processing time) would it be to use a long double
for numbers that do not need, since you say that the precisions that you will meet are not fixed. So, you could do that with that code (kindly assembled by this and this answers and the std::numeric limits):
#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <limits>
typedef std::numeric_limits< double > dbl;
int main() {
std::ifstream ifile("example.txt", std::ios::in);
std::vector<long double> scores;
//check to see that the file was opened correctly:
if (!ifile.is_open()) {
std::cerr << "There was a problem opening the input file!\n";
exit(1);//exit or do additional error checking
}
long double num = 0.0;
//keep storing values from the text file so long as data exists:
while (ifile >> num) {
scores.push_back(num);
}
std::cout.precision(dbl::max_digits10); // you can print more digits if you like, you won't the exact representation obviously
//verify that the scores were stored correctly:
for (int i = 0; i < scores.size(); ++i) {
std::cout << std::fixed << scores[i] << std::endl;
}
return 0;
}
which gives on my machine:
C02QT2UBFVH6-lm:~ gsamaras$ cat example.txt
3.12345678912345678912345678 2.79
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
3.12345678912345679
2.79000000000000000
If you want to go even further, then use GMP, which is "a free library for arbitrary precision arithmetic". Of course, this will won't come for free in terms of memory usage and processing time, so you should really think twice before using it!
*I feel that you are a victim of premature optimization. If I were you, I would just store the strings and see how this is going, or better yet use a numeric data type, thus losing some precision, making your life far easier. When the project is ready see what results you are getting and if the precision achieved pleases "your boss". If not, use strings (or gmp).