Reputation: 333
Hello for my program I must validate input for multiple arrays in another function. So say I have an array: barcode[MAX]. I want the user to input their barcodes into this array, so like however many barcodes they have they would input it into the barcode[MAX] variable. I would need to validate this input to make sure that it is proper format, so basically greater than 0, no trailing characters. And this validation needs to come from a separate function.
So it would be something like:
for (i = 0; i < MAX; i++)
{
printf ("Barcode: ");
barcode[MAX] = validate();
printf ("Price: ");
price[MAX] = validate();
}
that would be in the main function, calling the user to input their barcodes / prices and validating the input in a separate function. But I am not sure how to write a validating function for an array input. I have written one before for just a simple variable but an array confuses me. My previous validating code was like:
do
{
rc = scanf ("%llf%c", &barcode[MAX], &after);
if (rc == 0)
{
printf ("Invalid input try again: ");
clear();
}
else if (after != '\n')
{
printf ("Trailing characters detected try again: ");
clear();
}
else if ()
{
}
else
{
keeptrying = 0;
}
} while (keeptrying == 1);
but this doesn't look like it would work for an array variable and that was the code I would use for a non array variable. How can I fix this? Also the two arrays are different data types. barcode is a long long variable and price is a double variable.
Upvotes: 1
Views: 714
Reputation: 51393
You want to iterate over the array so is barcode[i] and not the fix position MAX (barcode[MAX]).
for (i = 0; i < MAX; i++)
{
printf ("Barcode: ");
barcode[i] = validate();
printf ("Price: ");
price[i] = validate();
}
Replace long long float for float, you can't use long long float in c.
Validate can be something like this:
int validate()
{
char after;
float input;
int rc, keeptrying = 1;
do
{
printf("Give me a code bar :\n");
rc = scanf ("%f%c", &input, &after);
if (rc == 0)
{
printf ("Invalid input try again: \n");
while ( getchar() != '\n' );
}
else if (after != '\n')
{
printf ("Trailing characters detected try again: \n");
while ( getchar() != '\n' );
}
else
keeptrying = 0;
} while (keeptrying == 1);
return input;
}
Upvotes: 2