473,883 Members | 1,763 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 6600
"Xancatal" <pe**********@g mail.comwrites:
[...]
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);
The "%c" format expects a pointer to the first element of a character
array. With no length specified, the length defaults to one. A
single character object, in this context, acts like an array of length
one. You didn't show us the declaration of otherVar, but for this to
work, it should be of type char. So this is a (somewhat convoluted)
way to read a single character.
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.
&otherVar is the address of your char variable, so it's of type char*
(pointer-to-char). You can't assign a char* to a float; it doesn't
even make sense to try.

Part of the problem is that there are multiple ways to do what you're
trying to do.

One of the most general ways to handle text input is:

Use fgets() to read a whole line at a time into a string. Note
that the resulting string will usually contain the '\n' character
that terminated the line. (If the input line is longer than your
buffer, or if you hit end-of-file or an error, things can get more
complicated.)

Use sscanf(), or perhaps some more specific function like
strtol(), to extract the data from the string.

You *can* use scanf(), but it combines reading input and parsing it
("parsing" means analyzing data in a sequence of characters, either a
string or an input file), and it doesn't respond well to errors.
Using fgets() and sscanf() separately, if sscanf() fails, you can
easily discard the entire line, or try again with a different format.
scanf() or fscanf() is less flexible; if there's an error, it's
already consumed some amount of input.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 24 '06 #21
"Nick Keighley" <ni************ ******@hotmail. comwrites:
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()***.
scanf is flawed to an extent that it is barely useful, because it
yields undefined behavior if out-of-range data is input. See C99
7.19.6.2p10:

...if the result of the conversion cannot be represented
in the object, the behavior is undefined.

I am amazed that the committee did not fix this in C99.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Oct 24 '06 #22
In article <11************ **********@h48g 2000cwc.googleg roups.com>
Xancatal <pe**********@g mail.comwrote:
>... 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.
If you really want to scan "dollar amount"s, you might find some
code I have lying around here useful.

The comp.lang.c folks can do their usual work on this to improve
it. :-)

(I have removed some parts that are not relevant, but left others
in since I have little time to make this posting. If I had more
time I could post a shorter article. Some additional editing will
be required to make this compile.)

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char whitespace[] = " \t";

static void read_line(char *, int, char *);
static int getdouble(char **, double *, int);

int
read_input(char *fname, FILE *in)
{
int c;
char *p;
int lineno = 0;
char line[BUFSIZ];

while ((p = fgets(line, sizeof line, in)) != NULL) {
lineno++;
p = strchr(p, '\n');
if (p == NULL) {
/* not the best, but ... */
printf("%s:%d: overlong input line truncated\n",
fname, lineno);
while ((c = fgetc(in)) != EOF && c != '\n')
continue;
} else
*p = '\0';
read_line(fname , lineno, line);
}
return 0; /* XXX should return error count? */
}

/*
* Break the line into tokens, then act on them.
* This is a pretty cheesy lexer/parser but what the heck.
* We use the date parser to make sure the first (assumed to be date)
* field is sensible.
*/
static void
read_line(char *fname, int lineno, char *line)
{
char *p, *ep;
unsigned char c;
[snippage]
int rv;
double n2;

p = line;
p += strspn(p, whitespace);
if (*p == 0 || *p == '#')
return; /* ignore blank/comment lines */
ep = p;
[snippage -- code that extracted date, record type, etc]
if (getdouble(&ep, &n2, 1)) {
printf("%s:%d: malformed %s -- bad $ value\n",
fname, lineno, "line");
return;
}
[snippage]
}

#define COMMA ','
/*
* Rather stupid little algorithm to clean up "money style" numbers --
* replaces removed commas with trailing whitespace (ugh, but what
* the heck).
*/
static int
cleanmoney(char *st, char **epp)
{
size_t m;
char *t, *en;
enum { MAYBE, YES, NO } state;

en = *epp;
t = memchr(st, '.', en - st);
if (t != NULL) {
if (memchr(t + 1, COMMA, en - t - 1) != NULL)
return -1;
/* ok, no commas past decimal point */
} else
t = en;
m = t - st;
state = MAYBE;
while (m 3) {
/*
* there are at least 4 (more) digits; t points past
* the last of a group of 3 (incl eg to decpt or '\0'):
*
* "1,234.50"
* t
*
* Back it up 4 to point at the "possible comma".
* Reject if the 3 digits are a comma; then check/set
* state for comma-eating.
*/
t -= 4;
if (t[1] == COMMA || t[2] == COMMA || t[3] == COMMA)
return -1;
if (state == MAYBE)
state = t[0] == COMMA ? YES : NO;
if (t[0] == COMMA && state != YES)
return -1;
if (t[0] != COMMA && state == YES)
return -1; /* must be consistent */
if (state == YES) {
/* remove this comma */
memmove(t, t + 1, en - t - 1);
*--en = ' '; /* whack in a blank and shorten */
}
m -= 3;
}
*epp = en;
return 0;
}

/*
* Break off whitespace-separated token and turn it into a double
* via strtod. Allow "dollar" values (prefix $, embedded commas)
* if directed.
*
* Return 0 if that seemed to work.
*/
static int
getdouble(char **pp, double *result, int dollars)
{
char *cp, *ep, *ep2;
unsigned char c;

cp = *pp;
cp += strspn(cp, whitespace);
c = *cp;
if (dollars && c == '$')
c = *++cp;
if (!isdigit(c))
return -1;
ep = cp + strcspn(cp, whitespace);
if (dollars && cleanmoney(cp, &ep))
return -1;
*result = strtod(cp, &ep2);
if (ep != ep2)
return -1;
*pp = ep;
return 0;
}
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Oct 24 '06 #23
Bill Medland wrote:
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.
Something like this.
(You'll still have to tidy it up but hopefully it will give you enough to
get you going.)
/*
* Read in an amount in a very restrictive format
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
int main (int argc, char **argv)
{
/* I'm not proud of it but it should give Xancatal some pointers */
char buffer[20];
long cents = -1;
fprintf(stdout, "Enter an amount\n");
if (fgets(buffer, sizeof(buffer), stdin))
{
const char *p;
/* Skip over leading spaces, tabs etc. */
for (p = buffer; isspace(*p); p++)
;
if (isdigit(*p))
{
const char *first_digit;
const char *period;
first_digit = p;
for (; isdigit(*p); p++)
;
if (*p == '.')
{
period = p;
p++;
for (;isdigit(*p); p++)
;
if (*p == '\0')
{
fprintf(stderr, "Oh dear, the buffer was too small\n");
}
else if (*p != '\n')
{
fprintf(stderr, "Invalid additional input %s\n", p);
}
else if (p-period != 3)
{
fprintf(stderr, "Expected two figures after the
point\n");
}
else
{
char *end1;
char *end2;
cents = 100 * strtol(first_di git, &end1, 10) +
strtol(period+1 , &end2, 10);
assert(end1 == period);
assert(end2 == p);
assert(cents >= 0);
}
}
else if (*p == '\0')
{
fprintf(stderr, "Oh dear, the buffer was too small\n");
}
else if (*p != '\n')
{
fprintf(stderr, "Invalid additional input %s\n", p);
}
else
{
char *end;
cents = 100 * strtol(first_di git, &end, 10);
assert(end == p);
assert(cents >= 0);
}
if (cents >= 0)
fprintf(stdout, "You entered %ld cents\n", cents);
}
else if (*p == '\0')
{
fprintf(stderr, "Oh dear, the buffer was too small\n");
}
else
{
fprintf(stderr, "Invalid input %s\n", p);
}
}
else if (ferror(stdin))
perror("Error reading input");
else
{
assert(feof(std in));
fprintf(stderr, "No input\n");
}
return 0;
}
--
Bill Medland
Oct 24 '06 #24
/*
* Read in an amount in a very restrictive format
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
int main (int argc, char **argv)
{
/* I'm not proud of it but it should give Xancatal some pointers */
Bill,

Thanks for the code. I was unable to compile it though. I get this
error:

C:\Documents and Settings\Admini strator\My
Documents\dolla rProject\regist ersNevada\test. c: line 16: incompatible
types in initializer
'long cents = -1'
aborting compile

Any clues?

Oct 25 '06 #25
av
On 23 Oct 2006 08:56:42 -0700, 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

you have just to write the right getl_() for get the line
and sscanf_m like sscanf (that return error if oveflow too)

// se ritorna 1=valore preso in val
// altrimenti valore non preso
int
get_double(doub le* val, double min, double max, FILE_m* pf)
{char a[512];
int k, i=0, cf1;
la0:;
k=getl_m(a, 512, pf); cf1=cf();
if(k==0){if(cf1 ==1)
{laa:; printf("\n"); return 0;}
printf("Errore linea troppo lunga"); goto la2;
}
if( (k=sscanf_m(a, "%f", val))!= 1 )
if(cf1==1) goto laa;
if(k!=1||*val<m in||*val>max)
{la1:;
printf("Errore o importo fuori range");
la2:;
if(++i>=3) goto laa;
printf(": Riprova ");
goto la0;
}
return 1;
}

usage:
double val;
printf("Inseris ci il valore ");
if( get_double(&val , 0.0, 12.0, stdin) )
return 0;

Oct 25 '06 #26
av wrote:
On 23 Oct 2006 08:56:42 -0700, 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.

you have just to write the right getl_() for get the line
and sscanf_m like sscanf (that return error if oveflow too)

// se ritorna 1=valore preso in val
// altrimenti valore non preso
int
get_double(doub le* val, double min, double max, FILE_m* pf)
{char a[512];
int k, i=0, cf1;
la0:;
k=getl_m(a, 512, pf); cf1=cf();
if(k==0){if(cf1 ==1)
{laa:; printf("\n"); return 0;}
printf("Errore linea troppo lunga"); goto la2;
}
if( (k=sscanf_m(a, "%f", val))!= 1 )
if(cf1==1) goto laa;
if(k!=1||*val<m in||*val>max)
{la1:;
printf("Errore o importo fuori range");
la2:;
if(++i>=3) goto laa;
printf(": Riprova ");
goto la0;
}
return 1;
}

usage:
double val;
printf("Inseris ci il valore ");
if( get_double(&val , 0.0, 12.0, stdin) )
return 0;
congratulations . In only 20 lines of code you've used more gotos
than I've used in my entire career.
--
Nick Keighley

Soon I moved onto the hard stuff - computed goto. Lord, that was cool.
I
could jump to any of a dozen places with one line of code. Talk about
POWER!!
Richard Heathfield "goto: Just Say No."

Oct 25 '06 #27
Xancatal wrote:
>
>/*
* Read in an amount in a very restrictive format
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
int main (int argc, char **argv)
{
/* I'm not proud of it but it should give Xancatal some pointers */

Bill,

Thanks for the code. I was unable to compile it though. I get this
error:

C:\Documents and Settings\Admini strator\My
Documents\dolla rProject\regist ersNevada\test. c: line 16: incompatible
types in initializer
'long cents = -1'
aborting compile

Any clues?
Yes.
Either use int rather than long or use -1L for the constant.
--
Bill Medland
Oct 25 '06 #28
Bill Medland <bi*********@sh aw.cawrites:
Xancatal wrote:
>>
>>/*
* Read in an amount in a very restrictive format
*/
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
int main (int argc, char **argv)
{
/* I'm not proud of it but it should give Xancatal some pointers */

Bill,

Thanks for the code. I was unable to compile it though. I get this
error:

C:\Documents and Settings\Admini strator\My
Documents\doll arProject\regis tersNevada\test .c: line 16: incompatible
types in initializer
'long cents = -1'
aborting compile

Any clues?
Yes.
Either use int rather than long or use -1L for the constant.
No.

The declaration

long cents = -1;

is perfectly legal. The constant 1 has type int. Applying the unary
"-" operator yields a result of type int, with the obvious value. The
expression is used to initialize an object of type long, so it's
implicitly converted from int to long.

A diagnostic (warning message) is allowed, as it is for literally
anything, but it would be silly in this context, and I don't know of
any compiler that would issue a warning here. A compiler that rejects
the declaration either is badly broken, or is not a C compiler.

Something else is going on here, and changing "-1" to "-1L" is not
going to fix it (though it might conceivably work around it).

I compiled the code myself, and it compiled with no errors or
warnings. Perhaps Xancatal is doing something odd (using something
other than a C compiler, or compiling something other than the posted
source), but I have no idea what. If Xancatal can give us some more
details, we might be able to help.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 25 '06 #29
I compiled the code myself, and it compiled with no errors or
warnings. Perhaps Xancatal is doing something odd (using something
other than a C compiler, or compiling something other than the posted
source), but I have no idea what. If Xancatal can give us some more
details, we might be able to help.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Keith,

Thanks for your insight. I'm using a toy compiler as you can see. I
will try this out with a better compiler. I have Sun Studio 11 in
another system, but is quite complicated to compile and run simple
programs, for it develops more robust software. Does anyone know of a
better C compiler (perhaps a freebee?)

As soon as I get the compiler, I will re-try this code. I get all kinds
of weird errors when I try to compile this code as it is. :(

Oct 26 '06 #30

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
1760
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
4488
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
9796
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11153
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
10420
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...
0
9583
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
7975
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
7134
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
6002
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3239
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.