【发布时间】:2020-01-22 19:08:31
【问题描述】:
我正在使用 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”仍然存在)在记忆中)。我想我可能有类似this discussion 的问题,但我不是 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 降低一个值。即使只输入了1,再次要求输入时,输入 9 个字符也会减少到 8 个。
【问题讨论】:
-
您是否在代码中使用
cin >>以及cin.getline()?或从此流中提取的任何其他格式? -
另外,
*"\0"会触发我的 UB 感觉(尽管我对此不是 100% 确定)。你想要'\0'(单个字符)。 -
@Yksisarvinen ,我目前只使用 cin.getline() 。感谢您的更正,我的代码中有
"\0",但在编译器对我大喊大叫后添加了*。上面我也改了。 -
对我来说,我无法重现意外行为。
-
您的代码中有一些拼写错误,例如 ` cout ValidateInput 缺少结尾
}。也许只是放错了括号,因为现在while (!correctInputBool) {总是会遇到return userInput;,所以这种形式的循环没有意义。
标签: c++ validation cin getline input-buffer