I finally worked out all of the bugs in this bit of code. I'm pretty proud of it and I wanted to give it to all of you so that you could have it if you wanted it for any console programs that you make.
At the same time, this is ridiculous. C++ is double my age and there should seriously be a better way of getting valid, error free, inputs from the user. If anyone knows, please tell me.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
void gValid_Input(std::string& var, std::string question) {
using namespace std;
do {
cin.clear();
cin.sync();
cout << question;
// Code will not work as intended on Linux without the following
// but will work on windows (tested with g++)
// this must also be done after clearing, syncing cin
// and asking the question string otherwise the code will loop forever
if (cin.peek() == '\n'){
cin.ignore(1,'\n');
}
} while (!(getline(cin, var)));
}
template <typename t>
void gValid_Input(t& var, std::string question) {
using namespace std;
do {
cin.clear();
cin.sync();
cout << question;
} while (!(cin >> var));
}
void gValid_Option(char& response, std::vector<char> valid_Responses = {'y','n'}){
using namespace std;
const char diff = 'a' - 'A';
do{
cin.clear();
cin.sync();
cin >> response;
// Comment the following out if you care about getting an upper case answer
if (response >= 'A' && response <= 'Z'){
response += diff;
}
} while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}
void gValid_Option(char& response, std::string question, std::vector<char> valid_Responses = {'y','n'}){
using namespace std;
const char diff = 'a' - 'A';
do{
cin.clear();
cin.sync();
cout << question;
cin >> response;
// Comment the following out if you care about getting an upper case answer
if (response >= 'A' && response <= 'Z'){
response += diff;
}
} while (find(valid_Responses.begin(), valid_Responses.end(), response) == valid_Responses.end());
}