473,882 Members | 1,646 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
43 6598
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.
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.

>>
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>
--
Bill Medland
Oct 23 '06 #11
Xancatal wrote:
>
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.
Ah. Now we're getting somewhere.
In that case I would definitely use fgets(mystr,siz eof(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.
--
Bill Medland
Oct 23 '06 #12
Bill Medland wrote:
Fred Kleinschmidt wrote:
>"Xancatal" <pe**********@g mail.comwrote in message
>>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.

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

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Oct 23 '06 #13
CBFalconer wrote:
Bill Medland wrote:
>Fred Kleinschmidt wrote:
>>"Xancatal" <pe**********@g mail.comwrote in message
>>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..

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.

--
Bill Medland
Oct 24 '06 #14
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
Read in a string, Error check it, then convert it.
Oct 24 '06 #15
Xancatal wrote:

<snip>
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 misunderstandin g. 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>

--
Nick Keighley

Oct 24 '06 #16
Neil 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
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.

Oct 24 '06 #17

Nick Keighley wrote:
no no no! This is your fundamental misunderstandin g. 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>

--
Nick Keighley
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.

Oct 24 '06 #18
Xancatal wrote:
>
Nick Keighley wrote:
>no no no! This is your fundamental misunderstandin g. 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>

--
Nick Keighley

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.
--
Bill Medland
Oct 24 '06 #19

Bill Medland wrote:

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.
--
Bill Medland
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

Oct 24 '06 #20

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

Similar topics

5
8002
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
32346
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
1519
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
5273
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
7620
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
30437
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
4487
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
5486
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
9931
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...
0
11108
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10725
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10830
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
10403
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7956
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
5781
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...
1
4601
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.