I am using cin.getline() to store user input in a character array, and attempting to parse input to only allow numbers ranging from 1 to 4 to be entered. Things work fine under a specific set of circumstances: correct input is entered on the first try, OR 2 or less characters are entered, and correct input is entered after. An example is below.
[Expected behavior]
Enter input: 1 [ENTER]
Input accepted
[Expected behavior]
Enter input: rw [ENTER]
Incorrect input. Please try again.
Enter input: 1 [ENTER]
Input accepted
[Unexpected behavior]
Enter Input: rtw [ENTER]
Incorrect input. Please try again.
Enter Input: 1 [ENTER]
Incorrect input. Please try again.
Enter input: 1 [ENTER]
Incorrect input. Please try again.
[This will continue indefinitely]
I have tried everything from clearing the input buffer, to resetting the character array to null terminators in an attempt to see if it was still holding values from previous input (like in the unexpected behavior, if a "tw" was somehow still in memory). I think I may have a problem similar to this discussion, but I am not 100% sure. When I attempt to clear the input buffer, it waits for a second set of input, and I am unsure why. When I print the results of inputLength
, after an "unexpected behavior" run, it shows that there are still 2 or 3 characters in the array, when I have only entered 1. When removing cin.clear()/cin.ignore(), a second input is not needed, but then the above behavior happens. I appreciate any help.
I have posted relevant code below.
char* ValidateInput() {
const int maxInput = 25;
char userInput[maxInput] = { "\0" };
int inputLength = 0;
bool correctInputBool = false;
while (!correctInputBool) {
// subtract 1 to allow for null terminator at end of array
cin.getline(userInput, (maxInput - 1), '\n');
// I have tried both versions of cin.ignore() below, but neither works
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//cin.ignore(numeric_limits<streamsize>::max());
// calculate how many characters user entered
inputLength = sizeOfCharArray(userInput, maxInput);
// I do other things here, there isn't a problem with this. For now, assume all 1-character input is acceptable
if (inputLength == 1) {
cout << "Correct input." << endl;
correctInputBool = true;
}
if (!correctInputBool) {
cout << "Sorry, that input is incorrect. Please try again." << endl;
cout << "Please enter a number between 1 and 4." << endl;
}
return userInput;
}
int sizeOfCharArray(char input[], int maxSize) {
// all values in input are set to "\0", so count all characters that are not null
int userSize = 0;
for (int index = 0; index < maxSize; index++) {
if (input[index] != '\0') {
userSize++;
}
}
return userSize;
}
EDIT: I've noticed that when I input more than 3 characters, the next run will always drop the inputLength
down one value. Inputting 9 characters goes down to 8 when asking for input again, even if only 1
was input.