Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Code keeps crashing after a validation

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;
            }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading