Hey guys
I have some problem in my c++ program
hope you guys can give a hand

--------------------------------------------------------------------------------------------------------

do
        printf("Please key in the number of passenger >>");
        scanf("%s" , &no_passenger_check);

        if (strlen(no_passenger_check)>3)
        {
            repeat = 1;
        }else
            {               
                        if (isdigit(no_passenger_check[0,1,2]))
                            {
                                repeat = 0;
                            }
                        else
                        {
                            repeat = 1;
                        }
            }
    }while (repeat == 1);

---------------------------------------------------------------------------------

I wanna ask that is this (isdigit(no_passenger_check[0,1,2])) correct?
because I just want to check whether that the first three alphanumeric input that I entered is digit or not?
Is it correct?

Recommended Answers

All 3 Replies

You're gonna check each character one by one if it is in fact a digit.

okay
now i changed my code into like this

    do
    {
        printf("Please key in the number of passenger >>");
        scanf("%s" , &mass_passenger_check);

        if (strlen(mass_passenger_check)>3) //detects whether there is more than 3 alphanumerical input
        {
            repeat = 1;
        }else
            {               
                        if (!(isdigit(mass_passenger_check[0])))
                            {
                                if (!(isdigit(mass_passenger_check[1])))
                                {
                                    if (!(isdigit(mass_passenger_check[2])))
                                    {
                                        repeat = 1;
                                    }else
                                    {
                                        repeat = 0;
                                    }
                                }
                            }
            }
    }while (repeat == 1);

but got a lit bit problem faced that is, when I enter "as1" or "qw2", it wont repeat again yet it allow to proceed

Wouldn't it be simpler to defer that prefix algorithm to a separate function that returns a boolean?

for (;;) {
    printf("Please key in the number of passenger >> ");

    if (scanf("%s", &mass_passenger_check) && starts_with(mass_passenger_check, isdigit, 3)) {
        break;
    }
}

Writing such a function is trivial:

int starts_with(const char *s, int (*pred)(int), int n)
{
    while (--n >= 0) {
        if (!*s || !pred(*s++)) {
            return 0;
        }
    }

    return 1;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.