【发布时间】:2014-12-15 23:28:01
【问题描述】:
我正在尝试控制小型控制台应用程序的使用,并且不希望用户键入超过一个字符的任何内容。到目前为止我所拥有的
int main()
{
char choice;
string strChoice;
/*Set the title bar title to Binary Calculator*/
system("title Binary Calculator 2014");
do{
Menu();
getline(cin,strChoice);
choice = toupper(strChoice[0]); //convert value to uppercase for conformity
DetermineChoice(choice);
} while (mistakes < 3);
}
但是当我输入时
bbbbbbbb
屏幕出问题了(我相信它是由 do while 循环引起的)所以我只需要刷新除第一个字符之外的所有字符。此外,当我第一次运行程序时选择B,然后我返回并尝试再次选择B,它说我在输入缓冲区中除了回车之外什么都没有。
以上是我的 int main。我将向您展示确定选择功能和错误处理功能。
void DetermineChoice(char value)
{
/*
Purpose: Determine what character was passed to value
Pre: a hopefully valid character
Post: Will go through cases below and then pass to another function
*/
string binary;
int decimal;
switch (value)
{
case 'B':
case 'C':
ConversionOperation(value);
case 'P':
cout << "Process File" << endl;
break;
case '+':
case '-':
case '/':
case '*':
case '%': ArithmeticActions(value);
case 'Q':
PrintSummary();
break;
default:
HandleChoiceError(value);
break;
}
}
选择错误:
void HandleChoiceError(char value)
{
/*
Purpose: Handles the errorenous character passed
Pre: an invalid character
Post: Will output the error, pausing the screen then reprint the menu
*/
system("cls");
mistakes++;
cout << setw(40) << "The option you selected (" << value << ") is not a valid choice." << endl;
cout << setw(25) << "You have made " << mistakes << " mistake" << (mistakes > 1 ? "s" : "") <<" becareful only three allowed!" << endl;
cout << setw(60) << "Please press enter and try again" << endl;
if (mistakes < 3)
{
system("pause");
}
}
一些需要注意的事情::
我只能使用系统(所以请不要告诉我它很糟糕或资源占用!)
我不能使用fflush 或除cin.clear() 之外的任何冲洗
除了iostream、iomanip、fstream、string和ctype.h之外,我不能使用任何其他库
谢谢大家,我的程序现在可以正常工作了。
int main()
{
char choice;
string strChoice;
/*Set the title bar title to Binary Calculator*/
system("title Binary Calculator 2014");
do{
Menu();
if ( getline(cin, strChoice) )
{
choice = toupper(strChoice[0]);
DetermineChoice(choice);
cin.ignore(10000, '\n');
}
else
{
cout << "Something went wrong with the input, please restart the program and try again." << endl;
break;
}
} while (mistakes < 3);
return 0;
}
【问题讨论】:
-
std::getline,然后要么检测多个字符并发出一个错误,要么只处理第一个字符并忽略其余字符。 -
getline 不是也有问题吗?
-
您指的是什么问题?它吸收了直到
'\n'的所有内容,丢弃了'\n'并向您展示了这条线。如果该行长于单个字符,则您知道您输入了虚假输入。如果它有一个字符并且它不符合您的标准,再次,虚假输入。如果它有一个字符并且满足您的一个匹配项,那么您就可以开始了。也许你在想一些我没有(不太可能)的事情。 -
好的,是的,我记得问题是
getline然后使用cin >> choice或cin.get在系统暂停后我需要刷新缓冲区,我相信这就是冲突所在,但我在在第一部分用你的决议更新我的问题 -
我不知道你在说什么。我说的是
std::string line;std::getline(cin, line);` 并使用line来制作我上面描述的内容。cin >> choice和cin.get()在我所描述的内容中无处。您的代码更新似乎反映了这一点,那么问题是什么?执行此操作后,输入缓冲区不应需要刷新。