1

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.

4

1 回答 1

2

您想要遍历数组,barcode[i] 也是如此,而不是固定位置 MAX (barcode[MAX])。

for (i = 0; i < MAX; i++)
{
    printf ("Barcode: ");
    barcode[i] = validate();

    printf ("Price: ");
    price[i] = validate();
}

将 long long float 替换为 float,不能在 c 中使用 long long float。

验证可以是这样的:

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;
}
于 2012-11-11T20:39:39.283 回答