Reputation: 23
It is a part of whole codes. when i try to execute, it operate normally until "Enter month and payment received". However after this message, i put Hash index and value such that "July 315.14". Suddenly, it print "Another query(Y/N)?" in infinite loop. Where is my error point?
unordered_map<string,float> monthly_payment;
char query;
string month;
cout << "Enter number of payments : ";
cin >> payNum;
cout <<"Enter month and payment received : " << endl;
for(int i=0; i<payNum; i++){
getline(cin, month,'\n');
cin >> payment;
monthly_payment.insert(pair<string, float>(month,payment));
}
cout << "Enter query month : ";
getline(cin, month, '\n');
cout << "The payment is " << monthly_payment[month]<<endl;
do{
cout << "Another query (Y/N)? ";
cin >> query;
if(query=='Y'){
cout << "Enter query month : ";
getline(cin, month, '\n');
cout << "The payment is " << monthly_payment[month]<<endl;
}
}while(query!='N');
Upvotes: 0
Views: 67
Reputation: 560
When you have
int i;
string str;
cin >> i; // [1]
getline(cin, str); // [2]
It stops within [1] and waiting for user input.
Then user typed 32
and nothing happened. Then user hits <enter>
and input buffer flushes to process 32\n
.
Program parsed 32
at line [1] and goes to line [2]. It's \n
remains to parse so str
becomes empty string and program moves forward.
On linux you can make input buffer flash another way. Pressing Ctrl+D for example. So you program becomes usable.
The best way to solve your problem just have
string month;
double payment;
cin >> month >> payment;
Or as alternative you can use geline
everywhere and parse string by the hands.
Upvotes: 1