I am working on a program that has a registry system where you can register new members.
To give some context, the name you register has to be different than existing names, can only be one word, and is turned into all caps before being saved to a file. To avoid potential mistakes in file handling, I only want the usernames to be letters, no numbers or special characters.
Because I want to avoid leading and trailing white space the user may accidentally enter, I decided to store the new username being registered into a char array newName
, but I just cannot figure out how to properly go through the char array to check for any numbers or special characters so I can ask the user to enter a proper username instead. I've tried using different loop variations with isalpha()
function but haven't found anything yet.
Here is that section of my code, which as of now only says "sorry, wrong username"
no matter if I enter a username with numbers/special characters or just letters:
char newName[80];
bool valid;
do {
valid = true;
std::cin >> newName;
std::cin.sync();
for (int i = 0; i < 80; i++) {
if (!std::isalpha(newName[i]))
valid = false;
else
valid = true;
}
if (!valid)
std::cout << "Sorry, wrong username." << std::endl;
} while (!valid);
for (int i = 0; i < 80; i ++) {
if (newName[i] != '\0')
newName[i] = toupper(newName[i]);
else
break;
}
for (int i = 0; i < nameList.size(); i++) {
if (nameList.at(i) == newName) {
std::cout << "Sorry, this name already exists. If you are registering a new member, please enter a new name for them." << std::endl;
validName = false;
break;
}
if (nameList.at(i) != newName)
validName = true;
}