我正在使用 cin.getline() 将用户输入存储在字符数组中,并尝试解析输入以仅允许输入 1 到 4 之间的数字。在特定情况下一切正常:第一次尝试输入正确的输入,或者输入 2 个或更少的字符,然后输入正确的输入。下面是一个例子。
[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]
我已经尝试了从清除输入缓冲区到将字符数组重置为空终止符以尝试查看它是否仍然保存先前输入的值(例如在意外行为中,如果“tw”仍然在内存中) . 我想我可能有类似这个讨论的问题,但我不是 100% 确定。当我尝试清除输入缓冲区时,它会等待第二组输入,我不确定为什么。当我打印结果时inputLength
,在“意外行为”运行后,显示数组中仍有 2 或 3 个字符,而我只输入了 1。删除 cin.clear()/cin.ignore() 时,不需要第二个输入,但随后会发生上述行为。我很感激任何帮助。
我在下面发布了相关代码。
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;
}
编辑:我注意到当我输入超过 3 个字符时,下一次运行总是会inputLength
降低一个值。再次要求输入时,输入 9 个字符会减少到 8 个,即使只是1
输入。