Your message was an example of top posting. Whether you think it is
right or wrong, you will receive abuse and/or neglect for doing it.
It took me as much time to fix your post as it did to answer your question.
Wow chuck, you just went way over my head
I assume you mean using
the if conditional, but if you don't mind explaining what precisely
would "1 != to scanf..." really mean on this construct? How would this
verify the input is not alphabetic?
Now I would handle it more like this,
int rc;
float myvar;
if( (EOF == (rc=scanf("%f", &myvar))) || (rc !=1) || (myvar < 0.0) ){
/* handle error */
}
This can be done in one line because of the guaranteed left-to-right
evaluation of the logical or's. You could break it down into several
statements for the same result.
rc = scanf("%f", &myvar);
if(EOF != rc){
if(rc == 1){
if(myvar >= 0.0){
/* the value was acceptable */
}
}
} /* silently discards errors */
void error(char *s){
/* just for example */
fprintf(stderr, "%s\n", s);
exit(-1);
}
/* ... */
rc = scanf("%f", &myvar);
if(EOF == rc){
error("premature end of input");
} else if(rc != 1){
error("expected a float, got something else");
} else if(myvar < 0.0){
error("expected a nonnegative float, got something else");
} else {
/* the value was acceptable */
printf("%f\n", myvar);
}
scanf(...) returns a count of the number of successful assignments. In
this case, you have exactly one conversion specification in your format
string, which means the expected return from scanf(...) is 1. Scanf
could also return zero or EOF, either of which would be an error. You
also apparently only want nonnegative input values; I didn't see that
requirement in the maze of top-posting noise. But because myvar is
float in this example, it should be compared to a float 0.0, not an
integer 0 ;
In reality, I prefer not to use scanf(...) at all. I tend to write my
own input handlers based on fgetc(FILE *), and if I do want scanf(...),
I tend to use sscanf(const char *, const char *, ...) (Such a strategy
puts the programmer in more control; I'm not saying scanf(...) is
dangerous in the way gets() is, but I treat it the same.)