In the program I'm working on, I use std::getline twice in order for the user to enter two inputs relating to different attributes of a person: their name, and then their partisan identification. The program then asks the user if they want to include additional people, and if the user indicates that they do, it presents the prompts to the user again. My program works for the first person the user enters these attributes for. However, if I indicate that I want to add another person, the program "skips over" the first prompt, displaying the question but not actually allowing the user to add input. It also displays the second prompt at the same time, allowing me to respond to that prompt but not the first one. This problem repeats for each successive person I try to enter attributes for.
Image of the problem I described
I tried fixing this by including cin.ignore(100, 'n') at the end of my program, but that simply causes the program to stop functioning after I enter the first person's name and partisan identification and ask to enter attributes for more people. The program still runs but does not prompt me again as it should.
Here is my code:
// DelibDem.cpp : Defines the entry point for the application.
//
#include "DelibDem.h"
#include <stdio.h>
#include <vector>
//initializing variables
using namespace std;
bool continue_ = true;
string name = "";
string partyID = "";
int numD = 0;
int numR = 0;
int difference = 0;
int vectorSize = 0;
int newVectorSize = 0;
struct person{
string Name;
string PartyID;
string equivalentName;
string equivalenceClass;
};
vector<person> Sample;
int main()
{
//user adds people to the vector. I have not yet implemented the code that actually adds the people specified by the user yet, because I am still trying
//to figure out why my getline code is not working.
while (continue_ == true) {
string personName;
string personPartyID;
string answer;
person inputtedPerson;
cout << "Enter a person's name: ";
std::getline(cin, personName);
cout << "Enter the person's party ID (D or R): ";
std::getline(cin, personPartyID);
if (personPartyID == "D") person inputtedPerson = { personName, personPartyID, "", "Republicans" };
else person inputtedPerson = { personName, personPartyID, "", "Democrats" };
cout << "Do you wish to add more people? (Y/N) ";
cin >> answer;
if (answer == "N") continue_ = false;
}
//The number of Democrats in the sample is stored in numD. The number of Republicans is stored in numR.
for (auto& element : Sample)
{
if (element.PartyID == "D") numD++;
else numR++;
}
//print the number of Democrats and Republicans
cout << numD;
cout << numR;
//print the properties of each element in the sample
for (auto& element : Sample)
{
cout << element.Name << endl;
cout << element.PartyID << endl;
cout << element.equivalentName << endl;
cout << element.equivalenceClass << endl;
cout << "\n";
}
return 0;
}