Ad

C++ Code Keeps Crashing After A Validation

- 1 answer

I have written a piece of code to validate a keyword, it validates and makes sure that the word is 5 letters long and it is all letters with no numbers in it. However, when I run it, the code seems to stop working at all and doesn't prompt me for the next question, I've tested it without this code and this part of the code is the problem, as it works fine without it.

The code:

            cout<<name1<<", please enter the keyword (5 characters): "<<endl;
            cin>>key;
            for(int i = 0; i < keylength; i++){
                if(isalpha(key[i]) == 1){
                    validnum += 1;
                }
            }
            if(validnum == keylength && key.length() == keylength){
                validated = true;
            }
            else{
                validated = false;
            }
Ad

Answer

Before the for loop you need to check that key.length() is equal to keyLength. Otherwise the loop can invoke undefined behavior when the user enters a string with the length less than keyLength.

Also the function isalpha does not necessary returns 1. It can return any positive value.

Change your code something like the following

validated = key.length() == keyLength;

if ( validated )
{
    size_t i = 0;

    while ( i < keyLength && isalpha( ( unsigned char )key[i] ) ) ++i;

    validated = i == keyLength;
}
Ad
source: stackoverflow.com
Ad