0

I have been at this for hours now, trying to figure out why my code isn't letting me re-enter my name after I say I want to register again.

Here's the code:

#include <iostream> 
#include <string> 

using namespace std; 

int main() { 
    string full_name{}; 
    string answer{"yes"}; 

    while (answer1 == "yes" || answer1 == "Yes") { 
        string answer{}; cout << "Type your full name with a space inbetween: "; 
        getline(cin, full_name);
    
        cout << full_name << " has been registered" << endl; 
  
        cout << "Do you want to clear your name from the list :";  
        cin >> answer; 
    
        if (answer == "yes" || answer == "Yes") { 
            full_name.clear(); 
        }
    
        else if (answer == "no" || answer == "No") { 
            cout << "Your name is still in the list" << endl;      
        } 
    
        cout << full_name << endl; 
        string answer1{}; 
 
        cout << "\nDo you want to register again or someones else name?" << endl; 
        cin >> answer1; cout << endl; 
   
        if (answer1 == "no" || answer1 == "No") {  
            cout << "Thank you for registering" << endl; break; 
        }  
    }
} 

When I say yes to cout << "\nDo you want to register again or someones else name?" << endl;, it loops back up, but skips cout << "Type your full name with a space inbetween: "; getline(cin, full_name);

Below are images of what I mean:

image

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • Let me know if you need me to add comments to the code I forgot to do that before I posted sorry – Eduardo Farrier May 18 '21 at 21:07
  • Recommendation: reduce the amount of code you write before compiling and testing. If you write a few lines, just enough to do one easily testable thing, you'll find you have bugs much faster so they won't have time to build up and gang up on you and be able to resolve them faster because the bugs have a much smaller surface area to hide in. – user4581301 May 18 '21 at 21:18
  • You may want to convert the string to all lower case or all upper case before comparing. So for example, if I entered "yEs", you loop would not continue. – Thomas Matthews May 18 '21 at 21:18

1 Answers1

0

You need to use the member function ignore of the standard input stream something like

#include <limits>

//...

    cout << "\nDo you want to register again or someones else name?" << endl; 
    cin >> answer1; cout << endl; 
    if (answer1 == "no" || answer1 == "No") {  
    cout << "Thank you for registering" << endl; break;

    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );   
}

that removes the new line character '\n' from the input stream that is stored in the stream buffer after this statement

cin >> answer1;

before calling std::getline in the next iteration of the loop. Otherwise the next call of std::getline will read an empty string.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268