I’m trying to optimize my solution to a problem, which requires fast double scanning. I tried to implement a function which read a double from the standard input, but I failed. Could someone point me some simple code which implements this efficiently? Thanks in advance.
Note here is my attempt, which seems to have some problems:
#include <stdio.h>
#include <stdlib.h>
inline double getDouble(FILE *f = stdin) {
char tmp[20], ch;
bool seen = false;
double sign = 1.0;
short index = 0;
while((ch = getc(stdin)) != EOF) {
if(ch == '-') {
sign = -1.0;
continue;
}
if(ch == ' ' || ch == '\n') {
if(seen) break;
} else {
seen = true;
tmp[index++] = ch;
}
}
return sign * (double)atof(tmp);
}
int main() {
int n;
scanf("%d", &n);
double *d = new double[n];
for(int i=0; i<n; ++i) {
d[i] = getDouble();
}
for(int i=0; i<n; ++i) {
printf("%.5lf\n", d[i]);
}
return 0;
}
Input:
16
-2 -1 -4 -5
1 1 1 1
1.233 -435 -2.44
3
2 3 42 4
Edit: It can indeed be some faster as this, I estimate the following to be 2 to 3 times as fast, it will pass your input, but takes quite some assumptions, no guarantees outside the test sample 🙂