If you do if (isdigit(buffer[i])) and you are reading the number
-152.1548042 it will lead you to say that number is 152, or that you
have two numbers, 152 and 1548042. Just something unconsistent.
Fortunatley it has no difficulty at all work with things this way.
But if you store that into a string char *buffer and you do
strtod(buffer, &characterpointer) it will return -152.155, once
corrected the other thing. Some function for maintain all the
precision?. I thought that double would maintain more precision than
plain float, but it's just the same. Using setprecision to greater
number, of course.
With a little file I send as example it takse more digits, but with not
the desired precission.
The file: (takefloat.cpp)
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <ctype.h>
using namespace std;
double takeNumber(char*, char*);
int main(){
fstream file;
char name[255];
char buffer[255], numeric[50];
double number;
long int size;
cout << "File for reading: ";
cin >> name;
file.open(name, ios::in);
if (!file){
cerr << "NOT OPENED" << endl;
exit(1);
}
while (!file.eof()){
file.getline(buffer, 254);
number = takeNumber(buffer, numeric);
cout << setprecision(12);
cout << buffer << endl;
cout << "Numeric: " << numeric << "\t" << "Number: " << number << endl;
}
file.close();
system("PAUSE");
return 0;
}
double takeNumber(char* buf, char* numer){
double res;
char* dum;
int i = 0, j;
while (!isdigit(buf[i]) && buf[i] != '-'){
i++;
}
for (j = 0; isdigit(buf[i + j]) || buf[i+j] == '-' || buf[i+j] == '.'; j++)
numer[j] = buf[i + j];
res = strtod(numer, &dum);
return res;
}
The test.txt:
Hello this is the number: -254.1258777 Goodbye!
The result I get is number: -254.12588501
|