-
Number Validation
Hi,
I have to validate a number and my function isn't as good as I thought it was,
Code:
...snip
typedef struct {
char custcode [CUSTCODE_LEN];
char usernbr [USERNBR_LEN];
...snip
} record_mtncnx;
void eq_recon_process(char * input_file_name, FILE ** fp)
{
record_mtncnx input;
char buffer[USERNBR_LEN + NULL_SIZE];
...snip
/* grab the USERNBR to test */
strncpy(buffer, input.usernbr, USERNBR_LEN);
buffer[USERNBR_LEN + NULL_SIZE] = '\0';
/* validate the USERNBR - if a problem stop the process */
if(check_number(buffer, USERNBR_LEN))
...snip
/* the only two values allowed are numbers and spaces */
int check_number(char * number, int length)
{
int loop;
char buffer[USERNBR_LEN + NULL_SIZE];
strcpy(buffer, number);
buffer[USERNBR_LEN + NULL_SIZE] = '\0';
for(loop = 0; loop < length; loop++)
if(!isdigit(buffer[loop]))
if(!isspace(buffer[loop]))
return FALSE;
return TRUE;
}
this is okay until the value it receives is [..12.3..]
NOTE: dots = spaces
it is okay for spaces to be before the number or after the number, but of course not in between, I have had a think about this, but cannot think what to do,
tia,
-
One quick problem you have is that you're running past the end of your array. Consider:
Valid entried in the above array are:
Code:
array[0] = something;
array[1] = something;
The following is invalid, as it goes beyond the end of your array, and into memory that you do not rightly have access to tinker with:
Code:
array[2] = BadThings( TM );
How this ties into your code should now be apparent:
Code:
char buffer[USERNBR_LEN + NULL_SIZE];
...snip
/* grab the USERNBR to test */
strncpy(buffer, input.usernbr, USERNBR_LEN);
buffer[USERNBR_LEN + NULL_SIZE] = '\0';
See there? You are accessing the space just past the end of the array. The only valid cells are zero to declaration size minus one.
Thus, you can only use:
Code:
buffer[0] ... buffer[USERNBR_LEN + NULL_SIZE -1]
Now on to your original problem...
Read until you encounter a number. Then read until you don't encounter any more numbers. From that point on, if anything that isn't a space shows up, you don't have valid input. Otherwise if you reach the end of the string, you do.
Quzah.
-
>I have to validate a number and my function isn't as good as I thought it was
If you need to convert it as well, then you may want to check out the strtol example in Option 3. You could use the resulting 'endptr' to check the remaining string for non-whitespace.
-
thanks quzah, my schoolboy error of the day :(
thanks Dave, I'll use that ;)