I am creating a C++ program to validate book name using a function in c++. The function must return 1 if the input is valid and 0 if the input is invalid. Book name can only contain upper case, lower case characters, color(:), comma(,) and space (there should be no consecutive spaces, commas, and colons). And the maximum characters in a character array is 60.
I tried the following way but I am not getting the desired answer.
const int MAX_BOOK_NAME = 60;
bool isValidBookName(char bookName[MAX_BOOK_NAME])
{
int length = strlen(bookName);
if (length > 59)
{
return false;
}
for (int i = 0; i < 59; i++)
{
if (bookName[i] < 'A' || bookName[i] > 'Z' || bookName[i] < 'a' || bookName[i] > 'z' || bookName[i] != ' ' || bookName[i] != ':' || bookName[i] != ',')
{
return false;
}
}
return true;
}
int main()
{
char arr[60];
cout << "Please Enter Your Book Id : ";
cin.getline(arr, 60);
cout << "Your Entered Name is " << isValidBookName(arr) << endl;
}
length > 59is true, then you're already in trouble as that would mean the buffer is overflowed and you already have undefined behavior because of that.std::isalphafunction, as your way to check for letters is encoding-specific and C++ doesn't assume any specific encoding.for (int i = 0; i < 59; i++)disregard the string null terminator, and could go out into uninitialized areas of the array which lead to undefined behavior.