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;
}
CodePudding user response:
As mentioned in the comments, there is no need for any loops to determine if the key is 5 characters and is all alphabetic.
Using std::all_of will test if all the characters are alphabetic:
#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>
bool isValidData(const std::string& key)
{
return key.size() == 5 && std::all_of(key.begin(), key.end(), ::isalpha);
}
int main()
{
//Test data
std::string testKeys[] = {"1abcdef", "abcde", "abcdefghijkl", "a", "xyzab"};
for (size_t i = 0; i < std::size(testKeys); i)
{
// Output results
std::cout << testKeys[i] << " " << (isValidData(testKeys[i])?"OK":"BAD") << "\n";
}
}
Output:
1abcdef BAD
abcde OK
abcdefghijkl BAD
a BAD
xyzab OK
Also, if you took a look at your code, it is not clear what the goal of the code is without running the code. Compare that to the function isValidData
: if you say what that function has in it, it reads almost as your description:
"The key size must be 5, and all of the characters must be alpha".
CodePudding user response:
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;
}