I'm trying to check if the user has entered their name correctly, with or without space i.e. Joe Bloggs. They cannot have special characters or numbers in their name or it will pop up with an error message i.e. Jo3_Bl0ggs. What I'm trying to do is if they enter their name in the wrong format, an error message will be alerted and the program will ask the user to enter their name again, until they enter it correctly.
I'm using a while loop to do this so if it's correct, I change the value of the flag and break out of the loop, if not I'll rerun the setName() function which asks for their name.
However the problem I'm having is that if they enter for the first time and it's incorrect, it asks them to enter their name again and if the second input is correct a message will say "Welcome Joe Bloggs", but the loop will continue and ask them to enter their name in again.
The only way I can avoid this problem is if the first input is correct, but that kind of defeats the whole point of the try and catch block.
Below is the two functions I'm concerned with. If someone can point me in the right direction, then that would be great. I'm new to c++ which is why I'm a bit confused about this.
inputclass::inputclass(){//empty constructor}
void inputclass::validateName(string name){
int flag = 1;
while ( flag == 1){
try{
for (int i=0; i < name.length(); i++){
if (name[i] != ' '){
if (!isalpha(name[i])){
cout << "You have entered incorrectly. Please try again. " << endl;
cin.clear(); //I'm trying to clear input buffer but still doesn't work
cin.ignore(256, '\n');
setName();
throw 0; //do i need this?
break; //do i need breaks?
}else if(i == name.length()-1){
cout << "Welcome to the program " << name << endl;
flag = 2; //break out of while loop
break; //not sure if this does anything
}
}
}
}catch (int e){
cout << "There's been an error" << endl;
setName(); //until input is correct, this will ask the user for their name.
}
}
}
void inputclass::setName(){
string name;
cout << "Please enter your name: " << endl;
getline(cin, name);
validateName(name);
}
if (flag != 2)
after thewhile
loop in order to check for errors. – Pavelflag
can only be1
or2
consider changing it to abool
. You can also get rid of thebreak
statements since you have no logic after theif
/else
blocks – Captain Obvlious