【发布时间】:2017-04-11 13:03:05
【问题描述】:
我正在编写的程序中有两个 cin 验证函数 - 一个用于验证 int,另一个用于验证 double,同时确保用户无法输入 char 值。我遇到的问题是,有时该函数会在要求用户输入值后立即开始验证,就像在这种情况下:
cout << endl << "Enter transaction ID to edit : ";
toEdit = validateIntInput(toEdit, 1, MAX_TRANS);
或者这种情况:
cout << "How much are you adding? : " << char(156);
tVal = validateDoubleInput(tVal, 0.01, 999999998);
但是,在其他情况下,程序不会告诉用户他们的输入无效,而是简单地创建一个新行,就像在这种情况下:
cout << "What day of the month is the bill normally paid? (1 - 31) (You can change this later) : ";
paymentDay = validateIntInput(paymentDay, 1, 31);
或者这种情况:
cout << "Annual interest rate (%) : ";
annualInterestRate = validateDoubleInput(annualInterestRate, 0.01, 100);
validateIntInput 的代码是:
int validateIntInput(int paramToCheck, int minValue, int maxValue)
{
paramToCheck = 999999999;
string line;
while (getline(cin, line))
{
stringstream linestream(line);
linestream >> paramToCheck;
// if the first if is not included, the program will assume invalid input has been entered as soon as the user is asked for input
if (paramToCheck == 999999999)
{
cout << "";
paramToCheck = 0;
}
// if the input contains a string or is not within bounds, throw an error
else if (!linestream.eof() || paramToCheck < minValue || paramToCheck > maxValue)
{
cout << red << "Invalid input. Try again : " << white;
}
// if the input is valid, stop the loop and accept the input
else
{
break;
}
}
return paramToCheck;
}
validateDoubleInput 的代码是:
double validateDoubleInput(double paramToCheck, double minValue, double maxValue)
{
paramToCheck = 999999999;
string line;
while (getline(cin, line))
{
stringstream linestream(line);
linestream >> paramToCheck;
// if the first if is not included, the program will assume invalid input has been entered as soon as the user is asked for input
if (paramToCheck == 999999999)
{
cout << "";
paramToCheck = 0;
}
// if the input contains a string or is not within bounds, throw an error
else if (!linestream.eof() || paramToCheck < minValue || paramToCheck > maxValue)
{
cout << red << "Invalid input. Try again : " << white;
}
// if the input is valid, stop the loop and accept the input
else
{
break;
}
}
return paramToCheck;
}
注意:函数将值 999999999 分配给参数并在启动时检查此值的唯一原因是因为程序有时甚至在用户输入任何内容之前就抛出异常。 p>
我真的不知道这里可能出了什么问题 - 谁能帮我找出问题的根源?
提前感谢任何可以的人!
【问题讨论】:
-
你为什么要传递你从未使用过的参数(
paramToCheck)?使用局部变量。 -
@molbdnilo 完全不确定我为什么这样做!我现在已经解决了一些问题,所以如果不是原来的问题,那是一回事
-
在这种情况下 paramToCheck == 999999999 为什么要打印一个空格并将其设置为 0?
-
一个很常见的问题是在调用
getline时输入缓冲区中有一个换行符。