I'm trying to make a function that asks for a string input and then validates it. If the answer is not correct, the function asks them again for valid input with a while loop.
In order to validate the string input, I'm using a string array with all the possible answers to the question.
Because I'm using a string array I need to pass it into the function as a pointer.
The problem I'm running into is that to call the function properly currently I have to type this:
std::string possibleAnswers[3] = { "0","1","2" };
//find the length of the possibleAnswers array
int length = sizeof(possibleAnswers) / sizeof(possibleAnswers[0]);
//create a pointer that points at the string array
std::string* pointerPossibleAnswers = possibleAnswers;
//call function to validate input
std::string response = checkInput(pointerPossibleAnswers, length);
You'll also notice that I used
sizeof(possibleAnswers)/sizeof(possibleAnswers[0]
to find the length which I can't call within the function, because the pointer in the function points to an element in the array, not the entire array.
My function implementation is here:
std::string checkInput(std::string* pointerPossibleAnswers, int length)
{
std::string input;
//input = toLowerCase(input);
//create a boolean to continue to ask for input
bool isAsking = true;
while (isAsking)
{
std::getline(std::cin, input);
//for loop checks against possibleAnswer array
for(int i = 0; i< length; i++)
{
// dereference possibleAnswers pointer to the
//ith position of the array
if (input == *pointerPossibleAnswers)
{
isAsking = false;
//stop checking if a possible response is found
//break from the loop on next iteration
i = length;
}
//make the pointer point to the next spot
pointerPossibleAnswers++;
}
if (isAsking == true)
{
std::cout << "Invalid response, please enter a valid response." << std::endl;
//reset the pointer to point at original memory
//location
for (int i = 0; i < length; i++)
{
pointerPossibleAnswers--;
}
}
}
return input;
}
I was just wondering if there is an easier way to call the function, which is one or two lines something like:
std::string possibleAnswers[3] = { "0","1","2" };
std::string response = checkInput(pointerPossibleAnswers, length);
within two lines that's more efficient, because I have noticed that I'm copying and pasting a lot of code each time. I feel like there is a much more efficient way to do this with a class or a vector, given they have some built in methods for calling
std::vector
orstd::array
instead of a raw c-style array ofstd::string
? \$\endgroup\$