Hi guys, I am looking for a way to check for error. I have an array of names. The user will enter a name and it will check the list for that name. If that make is not correct, it will go back and ask the user to try again until he types "Quit" or gets the name correctly. This is what I have so far. I know that there is no loop besides the for loop that just makes sure the name is on the list. I have tried a while loop and that doesn't seem to work the way I want it to. Please let me know if you guys have a solution.

getline (cin, Command);
      Name[K].Firstname = Command;

  for ( T = 0; T<30 ; T++) {
       if( Name[T] == Name[K].Firstname)   //K is a static variable because this is a program that will run forever and will save each and every name within the Name[K]Firstname that the user enters.
        {
           cout << "Correct";
          
           break;
        }
      
        else
        {
           cout << "Invalid Species try again :"  << endl;
           
        }
      }
bool done = false;
while( !done )
{
  
    getline (cin, Command);
    Name[K].Firstname = Command;

    for ( T = 0; T<30 ; T++) 
   {
       if( Name[T] == Name[K].Firstname)   //K is a static variable because this is a program that will run forever and will save each and every name within the Name[K]Firstname that the user enters.
        {
           cout << "Correct";
           done = true;          
           break;
        }     
        else
        {
           cout << "Invalid Species try again :"  << endl;           
        }
      }
}

I have tried this but the problem with this is that the else is within the scope of the for loop. So if I type in something wrong, it will spam "Incorrect name" 30 times.

Then take the message out of the loop and figure out how to remember that the name wasn't found during the loop...

Then take the message out of the loop and figure out how to remember that the name wasn't found during the loop...

the whole point to have this is so that the user cannot go any further unless they have the correct name on the list. Also, I want it to say "Cannot find name" or something every time they get it wrong.

The else is in the wrong place. Move it after that for loop. When the for loop ends, check to see if variable done is still false. If it is, then display the error message.

If I move the else after the for, it just says illegal else without matching if (since the if is in the for loop)

Well, silly, you have to remove the else too! You can't just blindly move code around without first thinking about what you are doing. Change that else to an if statement as I mentioned previously.

This article has been dead for over six months. Start a new discussion instead.