getRegionTotal()
是我现在用于验证的函数。它工作得很好,因为如果用户输入类似“二十”或-7的东西,它不会接受它,它会一直询问新的值,直到它得到一个有效的值。但是,如果用户输入60.7的北部地区的事故数量,它将接受60并放弃.7部分。当它要求南部地区的事故数量时,它会给出正常指示和更具体的指示。如何使整数验证函数不接受浮点值?
//These will hold the number of accidents in each region last year
int northTotal = 0;
int southTotal = 0;
int eastTotal = 0;
int westTotal = 0;
int centralTotal = 0;
//passing 0 for northTotal, southTotal etc. because main doesn't know
//values of them until the function returns a value. When it returns a value
//it will go into the variables on the left. getRegionTotal will get the number
//of accidents for a region from the user and prompt the user using the string that
//is in the first argument.
northTotal = getRegionTotal("North", northTotal);
southTotal = getRegionTotal("South", southTotal);
eastTotal = getRegionTotal("East", eastTotal);
westTotal = getRegionTotal("West", westTotal);
centralTotal = getRegionTotal("Central", centralTotal);
int getRegionTotal(string regionName, int regionTotal)
{
//instructs user to enter number of accidents reported in a particular region
cout << "\nNumber of automobile accidents reported in " << regionName << " " << cityName << ": ";
//while regionTotal is not an integer or regionTotal is negative
while (!(cin >> regionTotal) || (regionTotal < 0))
{
//give user more specific instructions
cout << "\nPlease enter a positive whole number for the number of\n";
cout << "automobile accidents in " << regionName << " " << cityName << ": ";
cin.clear(); //clear out cin object
cin.ignore(100, '\n'); //ignore whatever is in the cin object
//up to 100 characters or until
// a new line character
}
//returns a valid value for the number of accidents for the region
return regionTotal;
}
为什么不解析浮点数并使用强制类型转换为int,或者检查解析的数字是否有小数位(例如使用模运算符)? – Jost
小数位将自动删除。我不知道如何使用模数运算符来检查它。如果我将while循环条件更改为'while(!(cin >> regionTotal)||(regionTotal <0)||(regionTotal%1!= 0))'问题仍然存在 – user2234760
您需要_parse_一个float而不是int - 后来你转换它(但它只是一个想法 - 它有点肮脏;-)) – Jost