1

I'm having issues with the getline function. I apologize in advance if my code is not detailed to the stackoverflow syntax. What I am experiencing is when I run the addMember(), it prompts the user to enter name, which is then checked to see if it already exists. Once it passes it then moves on to ask the user for a password. If all goes well, it is then pushed into the vector memberlist. From there I should be able to exit and login in as the new member. What is printed when I immediately call this function is "Please enter name of member: Enter desired password: ." It completely skips over the point to which the user should be allowed to type a name and goes straight to entering a password. I understand that I need to use cin.ignore(1000, '\n'), but all that does is snip off either the name or password from the memberlist. For example: when I enter a username, it reads in correctly but the password reads in the newline character at the end of the previous getline. Are there any solutions out there to this issue other than reworking it in the main? Please help! Thanks!

void Staff::addMember() {
        string name;
        string password;
        bool alreadyexists = false;
        cout << "Please enter name of member: ";
        getline(cin, name);

        if (name.length() == 0) {
            cout << "You must enter a name. Please try again." << endl;
            addMember();
        } else {
            for (unsigned int i = 0; i < memberlist.size(); i++) {
                if (memberlist[i].getName() == name) {
                    alreadyexists = true;
                    cout << "That user already exists. Please try again." << endl;
                    addMember();
                }
            }
        }
        if (alreadyexists == false) {
            cout << "Enter desired password: ";
            getline(cin, password);
            cout << password;

                Member newMember(name, password);

                cout << "At time of instance " << newMember.getName() <<endl;
                memberlist.push_back(newMember);
                cout << "A new member has been added!" << endl;
                for (unsigned int i = 0; i < memberlist.size(); i++)
                    {
                        cout << memberlist[i].getName() << "\t"<< memberlist[i].getPassword() << endl;
                    }
                cont();
        //  }
        }
        displayMenu();

    }

1 Answers1

0

The issue is that you don't understand the input stream and how getline works. You should read the references on cin.getline and cin.ignore to understand how they work.

If those resources don't clear it up for you, there are lots of answers on this site to the same question, like this one. Good luck!

Community
  • 1
  • 1
Spencer Moran
  • 2,530
  • 3
  • 15
  • 13