Get input from various types c++

PHOTO EMBED

Thu May 14 2020 00:41:12 GMT+0000 (Coordinated Universal Time)

Saved by @Retchut #C++

enum InputMode {
	IntegerInput = 0, StringInput
};


std::string InputValidity(int mode) {

	std::string input;

	//bool invalid = true;

	while (true) {

		std::getline(cin, input);

		switch (mode)
		{
		case IntegerInput:

			int intTest;
			sscanf_s(input.c_str(), "%d\n", &intTest);

			if (intTest >= 2 && intTest <= 4) {
				return input;
			}
			else
			{
				cout << "Invalid input. The number of players must be 2-4.\n";
			}
			break;

		case StringInput:

			std::string strTest = input.substr(input.size() - 4);

			if (strTest == ".txt")
			{
				return input;
			}
			else {
				std::cout << "That input is invalid" << std::endl;
			}
			break;
		}
	}
}

int GetIntInput() {

	cout << "Please input the number of players (2-4): ";
	int returnedVal;
	std::string returnedString = InputValidity(0);
	sscanf_s(returnedString.c_str(), "%d\n", &returnedVal);
	cout << returnedVal << std::endl;

	return returnedVal;
}

std::string GetStrInput() {

	cout << "Please input the name of the board you wish to open (in the format \"<name>.txt\"): ";
	std::string returnedStr = InputValidity(1);
	return returnedStr;
}
content_copyCOPY

The enum is just there to improve the readability. We can add modes to it as we see fit. The switch statement is used for checking conditions the input must follow.