'Ello. I've recently decided to pick up programming. The books I bought have been doing me well, however, I have one problem that I don't have answered. I was going to write a program to find the mode of the elements in a vector until one glaring problem I've been having reoccured. Here's my code up to this point:
#include <iostream>
#include <vector>
usingnamespace std;
int get_int();
bool get_confirm();
int main () {
vector<int> v_userinput;
int userinput = 0;
bool get_vector = true;
cout << "Enter your numbers: " << endl;
do {
userinput = get_int();
v_userinput.push_back(userinput);
get_vector = get_confirm();
} while (get_vector);
return 0;
}
int get_int() {
int number;
while (1) {
number = 0;
cin >> number; // Problem!!!
if (cin.good()) {
return number;
} else {
cout << endl << "Invalid input.";
}
}
}
bool get_confirm() {
char yorn = 'Y';
cout << "Continue? Y or N: ";
while (1) {
bool is_yorn = false;
bool valid_choice = false;
while (!is_yorn) {
while (!valid_choice) {
cin >> yorn; // Problem!!!
if (cin.good()) {
valid_choice = true;
}
if (!valid_choice) {
cout << "Invalid input." << endl;
}
}
if (yorn != 'Y' && yorn != 'N' && yorn != 'y' && yorn != 'n') {
is_yorn = false;
valid_choice = false;
cout << "Invalid input." << endl;
}
}
if (yorn == 'Y' || yorn == 'y') {
returntrue;
} else {
returnfalse;
}
}
}
The problem is in the get_confirm function, in the loops on lines 41 and 25 . It seems to completely ignore "cin >> number" on any consecutive loops. I have no idea what causes this behavior, so any help explaining as to why it does so would be appreciated, along with any other possible improvements to the existing code.