473,811 Members | 2,979 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

verify float number

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

Oct 23 '06 #1
43 6590
Xancatal wrote:
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?

--
Bill Medland
Oct 23 '06 #2
Xancatal wrote:
>
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.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

Oct 23 '06 #3
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?

Bill Medland wrote:
Xancatal wrote:
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?

--
Bill Medland
Oct 23 '06 #4
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,

CBFalconer wrote:
Xancatal wrote:

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.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Oct 23 '06 #5
Xancatal wrote:
>>scanf ("%f", &myVar)
if ((1 != scanf(%f, &myvar)) || (myvar < 0)) {
/* handle bad entry */
}
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("prematur e 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.)

Oct 23 '06 #6

"Xancatal" <pe**********@g mail.comwrote in message
news:11******** **************@ b28g2000cwb.goo glegroups.com.. .
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.

>
CBFalconer wrote:
>Xancatal wrote:
>
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.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Oct 23 '06 #7
Xancatal wrote:
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().
>
Bill Medland wrote:
>Xancatal wrote:
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?

--
Bill Medland
--
Bill Medland
Oct 23 '06 #8

Fred Kleinschmidt wrote:
"Xancatal" <pe**********@g mail.comwrote in message
news:11******** **************@ b28g2000cwb.goo glegroups.com.. .
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.

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.

Oct 23 '06 #9

Bill Medland wrote:
Xancatal wrote:
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().
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.

Oct 23 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7998
by: Bryan R. Meyer | last post by:
I am a relatively new C++ programmer and am attempting to write a function that takes a number of type float and adds commas to it in the appropriate places. In order to manipulate the number to add the commas, I convert it to a string (specifically a char rather than an actual string object) using the gcvt function as shown below. char amt; gcvt(amount,50,amt);
0
1759
by: Support | last post by:
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv=Content-Type content="text/html; charset=windows-1252"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 11"> <meta name=Originator content="Microsoft Word 11">
2
32334
by: Goran | last post by:
Hi! I need to convert from a unsigned char array to a float. I don't think i get the right results in the program below. unsigned char array1 = { 0xde, 0xc2, 0x44, 0x23}; //I'm not sure in what order the data is stored so i try both ways. unsigned char array2 = { 0x23, 0x44, 0xc2, 0xde}; float *pfloat1, *pfloat2;
2
1517
by: Chris | last post by:
Hi The following code is giving strange results........... float fTest = 536495.61f; cout << _T("float: ") << fTest << endl; int dec, sign; char* pszTest = _fcvt(fTest, 10, &dec, &sign); cout << _T("string: ") << pszTest << endl;
2
5269
by: Wayne Wengert | last post by:
I want to write a Windows application to go through all the email addresses in an SQL Server table and to report which ones are invalid. From Googling and perusing NGs it is my understanding that the process to validate an email address is done at 3 levels: 1. Verify that it is syntactically valid 2. Verify that the domain exists (SMTP verification) 3. Verify that the email address exists at that domain (MX verification) The first one I...
6
7616
by: karthi | last post by:
hi, I need user defined function that converts string to float in c. since the library function atof and strtod occupies large space in my processor memory I can't use it in my code. regards, Karthi
7
30391
by: Partho | last post by:
I have a float variable which I need to add to a short variable. How do I do this? Do I have to typecast or is there a way around? I tried typecasting the float to a short, but that gives me a 0 or +/-1, which is unacceptable. Any pointers to how to get over this?
7
4478
by: DirtyRasa | last post by:
Here is what my professor told me to to. Write a function that converts a string to a float and returns a float. Test your function by entering f4 and with 4f. Both should say Data entered was not a number. Try again. and ask the user to type in another number. Here's what I have so far. Code:
2
5480
by: alishaikhji | last post by:
I am working on a program which will need several different integer and float random numbers at different stages, for example: - At one point, I need a random number (float) in the range 0.1 to 10.0 - At one point, I need a random number (float) in the range 0.5 to 1.5 - At one point, I need a random number (float) in the range 0.3 to 3.0 - At one point, I need a random number (float) in the range 0.1 to 10.0 Also, I need to make it sure...
0
9724
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10394
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9201
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5552
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.