Solution to scanf 9.9999999 as a float ?

Letalis Sonus

Advanced Member
Joined
Mar 5, 2009
Messages
1,321
Why does f need to be a float there if it's only ever going to receive an integer value, if I'm reading it right?
On the one hand: atof() even returns a double, you could simply use atoi() instead if that was the case. On the other hand: it will always end the string after 2 characters behind the '.' and therefore you won't get integers only.

However, the loop condition is still wrong: the length safety check i < 64-3 will stop the loop when i == 64-3, which means it would try to set input[64] afterwards - that's an OOB error.
 

levi

Still fresh, damnit!
Joined
Oct 6, 2008
Messages
11,955
Location
Somewhere off the coast of the EU
Ah yeah, that tricksy +3. I kind of assumed on reading that code was to pull the int off the front so you could test it wasn't 9 or lower. Replace the dot with a \0 to grab the int via atoi then back to a dot to run atof on it to get the value as a double, having already tested the int.

Something like (shamelessly cribbed from rohzeal and hacked):

Code:
char input[64];
gets_s(input, 64);

int i = 0;

while(input[i] != '.' && i < 64-1) {
i++;
}

input[i] = 0; //binary 0, Ends the string

int chk=atoi(input);

if chk<10 {
   /* TODO: Error */
}
else {
  input[i]='.'
  double f = atof(input);
}
Untested, of course.
 
Top