verify float number

X

Xancatal

Hey everybody. I need help on this one. I need to verify that a number
entered by a user is not either a negative number (-100.00), or an
alphabet (a, b, c, X, Y) as well as other number other than positive
integers or a decimal point. For example:

Enter amount:

and was capturing the float varialbe as in:

scanf ("%f", &myVar)

I was using scanf to capture the data, but I'm having a hard time
verifying this float with isdigit or isalpha. Any ideas would be
greatly appreciated.

Thanks
 
B

Bill Medland

Xancatal said:
Hey everybody. I need help on this one. I need to verify that a number
entered by a user is not either a negative number (-100.00), or an
alphabet (a, b, c, X, Y) as well as other number other than positive
integers or a decimal point. For example:

Enter amount:

and was capturing the float varialbe as in:

scanf ("%f", &myVar)

I was using scanf to capture the data, but I'm having a hard time
verifying this float with isdigit or isalpha. Any ideas would be
greatly appreciated.

Thanks
Sorry; it doesn't work that way. C is a lower level language than that.
If you use scanf then it will do its best to read in and do the conversion
for you (and stop once it gets to a bit that doesn't fit)
If you really want to do low level checking you will need to read in the
string as a string and then parse it yourself.
However you can test to see if the number is negative.
Why don't you just read the number in as an integer?
 
C

CBFalconer

Xancatal said:
Hey everybody. I need help on this one. I need to verify that a number
entered by a user is not either a negative number (-100.00), or an
alphabet (a, b, c, X, Y) as well as other number other than positive
integers or a decimal point. For example:

Enter amount:

and was capturing the float varialbe as in:

scanf ("%f", &myVar)

I was using scanf to capture the data, but I'm having a hard time
verifying this float with isdigit or isalpha. Any ideas would be
greatly appreciated.

if ((1 != scanf(%f, &myvar)) || (myvar < 0)) {
/* handle bad entry */
}

Always check input routine calls for errors.
 
X

Xancatal

Thanks for your response Bill. Do you mean read as integer and then
parse it? How about converting it then to float? would that be
possible? Do you have maybe an example I can go by?

I wast thinking I could use getchar to capture the stream from the
float (or the user), do the verification (you know... No weird
characters like $&# and so on as well as no letters), and then
calculate my float vars. Waddaya think?
 
X

Xancatal

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? I'm sorry for my lack of C language
Chuck, I apologize.

Thanks,
 
F

Fred Kleinschmidt

Xancatal said:
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? I'm sorry for my lack of C language
Chuck, I apologize.

Thanks,

scanf returns the number of fields that it successfully read.
So if the return value of scanf is one, it means
that is successfully read one field. Since you specified the
field to be a float, it successfully read one float value.

However, this may not be enough for you.
What happens if the user types in " 1.34q" ?
Do you want this to be an error? scanf() will return one
here.

Perhaps you should read the whole line in as a string,
then us strtod to check for errors. Note that strtod()
returns a double, not a float.

 
J

jmcgill

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.)
 
B

Bill Medland

Xancatal said:
Thanks for your response Bill. Do you mean read as integer and then
parse it?
No, you don't parse it. if you've read it then the characters have already
been parsed; it's now an int.
How about converting it then to float? would that be
possible? Do you have maybe an example I can go by?

I wast thinking I could use getchar to capture the stream from the
float (or the user), do the verification (you know... No weird
characters like $&# and so on as well as no letters), and then
calculate my float vars. Waddaya think?

My first preference would be simply
if (scanf("%d", &myint) != 1)
and accept that some input will be unused.
If I wanted to be more resilient I'd probably use fgets() and strtol().
 
X

Xancatal

Fred said:
scanf returns the number of fields that it successfully read.
So if the return value of scanf is one, it means
that is successfully read one field. Since you specified the
field to be a float, it successfully read one float value.

However, this may not be enough for you.
What happens if the user types in " 1.34q" ?
Do you want this to be an error? scanf() will return one
here.

Perhaps you should read the whole line in as a string,
then us strtod to check for errors. Note that strtod()
returns a double, not a float.

Thanks Fred. I'm learning among other things that I need to post below.
In essence, what I need is simple: Enter a dollar amount such as
100.00. Verify that this float (in my definition) is not anything other
than numbers and the decimal point "." I guess alphabeticals and
special characters is out of the question. So I then calculate another
amount using this first float. For example:

float myVar = 0;

printf ("\nEnter amount: ");
scanf("%f", &myVar);

I would then have to verify that this variable (myVar) does not contain
letter and special characters, in other words, positive numbers and
decimals. I tried using isdigit, but it only works with character type
variables. I am looking into creating an array of type float and then
maybe verify this way.
 
X

Xancatal

Bill said:
No, you don't parse it. if you've read it then the characters have already
been parsed; it's now an int.

My first preference would be simply
if (scanf("%d", &myint) != 1)
and accept that some input will be unused.
If I wanted to be more resilient I'd probably use fgets() and strtol().

Thanks Bill. I'm not familiar with fgets and strtol. I think fgets is
for file reading? In any case, what I have is something a lot more
simpler. Is only a matter of letting a user enter a dollar amount, and
letting the program determine if it is a dollar amount to do some
calculation, or otherwise prompt an error.
 
B

Bill Medland

Fred said:
scanf returns the number of fields that it successfully read.
So if the return value of scanf is one, it means
that is successfully read one field. Since you specified the
field to be a float, it successfully read one float value.

However, this may not be enough for you.
What happens if the user types in " 1.34q" ?
Do you want this to be an error? scanf() will return one
here.

No it won't (or am I missing something). It will read in 1.34 and then the
q will sit around waiting for the next call to scanf and mess that up..
Perhaps you should read the whole line in as a string,
then us strtod to check for errors. Note that strtod()
returns a double, not a float.
 
B

Bill Medland

Xancatal said:
Thanks Bill. I'm not familiar with fgets and strtol. I think fgets is
for file reading? In any case, what I have is something a lot more
simpler. Is only a matter of letting a user enter a dollar amount, and
letting the program determine if it is a dollar amount to do some
calculation, or otherwise prompt an error.
Ah. Now we're getting somewhere.
In that case I would definitely use fgets(mystr,sizeof(mystr), stdin)), look
carefully at the string and parse out the leading and trailing digits (look
up strchr).
If it's dollar amounts I probably wouldn't use float either; I would use an
integer and count in cents.
 
C

CBFalconer

Bill said:
No it won't (or am I missing something). It will read in 1.34 and
then the q will sit around waiting for the next call to scanf and
mess that up..

Which is exactly what you want. The termination char remains in
the stdin stream, you can check it as you please. This includes
'\n', so you can confidently flush the remainder of the input line
if you wish:

char flushln(FILE *f) {
int ch;
while (('\n' != (ch = getc(f)) && (EOF != ch)) continue;
return ch;
}

In general scanf is fairly well behaved when you restrict it to a
single input. The confusion becomes rampant when you want it to
detect multiple fields.
 
B

Bill Medland

CBFalconer said:
Which is exactly what you want. The termination char remains in
the stdin stream, you can check it as you please. This includes
'\n', so you can confidently flush the remainder of the input line
if you wish:

Ah: "scanf() will return one (the value 1)", not "scanf() will return one,
an error". I guess we talked past each other.
 
N

Neil

Xancatal said:
Hey everybody. I need help on this one. I need to verify that a number
entered by a user is not either a negative number (-100.00), or an
alphabet (a, b, c, X, Y) as well as other number other than positive
integers or a decimal point. For example:

Enter amount:

and was capturing the float varialbe as in:

scanf ("%f", &myVar)

I was using scanf to capture the data, but I'm having a hard time
verifying this float with isdigit or isalpha. Any ideas would be
greatly appreciated.

Thanks
Read in a string, Error check it, then convert it.
 
N

Nick Keighley

Xancatal wrote:

In essence, what I need is simple: Enter a dollar amount such as
100.00. Verify that this float (in my definition) is not anything other
than numbers and the decimal point "." I guess alphabeticals and
special characters is out of the question. So I then calculate another
amount using this first float. For example:

float myVar = 0;

printf ("\nEnter amount: ");
scanf("%f", &myVar);

I would then have to verify that this variable (myVar) does not contain
letter and special characters,

no no no! This is your fundamental misunderstanding. Take a deep
breath.
Most of the checking you want to do ***is done by scanf()***. myVar is
a float
it *cannot* hold letters or special characters. If you give scanf() a
correctly
formatted floating point number it will store the corresponding
floating point
value in myVar. If you give it something else it won't. scanf() makes
it difficult
to recover from errors, so (as others have suggested) use fgets() the
sscanf().
Once you have a floating point value you check for negative values or
out of range.

<snip>
 
X

Xancatal

Neil said:
Read in a string, Error check it, then convert it.

Thanks Neil, how do you think I could convert it? I tried this and it
failed during compile time:


float myVar = 0.0;
....
....
....

scanf ("%c", &otherVar);

myVar = &otherVar;

It looks as although I tried to assign the value of this string to the
float, it fails compilation. It says it can not assign value.
 
X

Xancatal

Nick said:
no no no! This is your fundamental misunderstanding. Take a deep
breath.
Most of the checking you want to do ***is done by scanf()***. myVar is
a float
it *cannot* hold letters or special characters. If you give scanf() a
correctly
formatted floating point number it will store the corresponding
floating point
value in myVar. If you give it something else it won't. scanf() makes
it difficult
to recover from errors, so (as others have suggested) use fgets() the
sscanf().
Once you have a floating point value you check for negative values or
out of range.

<snip>

Thanks Nick. In other words, if scanf does the checking, is it possible
then to use scanf or another function to check and make sure only
integers and a decimal point is allowed to be entered? If so, I think
this would solve my problem, because checking for negative number is
taken care of using a while loop.
 
B

Bill Medland

Xancatal said:
Thanks Nick. In other words, if scanf does the checking, is it possible
then to use scanf or another function to check and make sure only
integers and a decimal point is allowed to be entered? If so, I think
this would solve my problem, because checking for negative number is
taken care of using a while loop.
No (but do you want to be that restrictive).
Is the user allowed to enter 12e3 for 12000? scanf will allow that.
 
X

Xancatal

Bill said:
No (but do you want to be that restrictive).
Is the user allowed to enter 12e3 for 12000? scanf will allow that.

Bill,

Yes. In fact, I have it down to where it does not allow for negative,
or alphabets. However, the challenge now is to make sure no 12e3 or any
hybrids are allowed. In essence, to make sure only numbers and one
decimal, for example 100 or 100.00 but not -120 or 123ea2.00
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,177
Latest member
OrderGlucea
Top