Using scanf()
is problematic. If the user typed -5 +10 -15 -15
on the first line of input, then hit return, you'd process the 4 numbers in turn with scanf()
. This is likely not what you wanted. Also, of course, if the user types +3 or more
, then the first conversion stops once the space is read, and all subsequent conversions fail on the o
or or
, and the code goes into a loop. You must check the return value from scanf()
to know whether it was able to convert anything.
The read-ahead problems are sufficiently severe that I'd go for the quasi-standard alternative of using fgets()
to read a line of data, and then using sscanf()
(that extra s
is all important) to parse a number.
To determine whether a floating point number has a fractional part as well as an integer part, you could use the modf()
or modff()
function - the latter since your adj
is a float
:
#include <math.h>
double modf(double x, double *iptr);
float modff(float value, float *iptr);
The return value is the signed fractional part of x
; the value in iptr
is the integer part. Note that modff()
may not be available in compilers (runtime libraries) that do not support C99. In that case, you may have to use double
and modf()
. However, it is probably as simple to restrict the user to entering integers with %d
format and an integer type for adj
; that's what I'd have done from the start.
Another point of detail: do you really want to count invalid numbers in the total number of attempts?
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter=0;
int ttl=100;
printf("You all know the rules now lets begin!!!\n"
"\n\nWe start with 100. What is\n");
while (ttl != 5)
{
char buffer[4096];
float a_int;
float adj;
printf("YOUR ADJUSTMENT?");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
break;
if (sscanf("%f", &adj) != 1)
break;
if (adj<=20 && adj>=-20 && modff(adj, &a_int) == 0.0)
{
counter++; // Not counting invalid numbers
ttl += adj;
printf("The total is %d\n", ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
if (ttl == 5)
printf("The game is won in %d steps!\n", counter);
else
printf("No-one wins; the total is not 5\n");
return(0);
}
Clearly, I'm studiously ignoring the possibility that someone might type in more than 4095 characters before typing return.