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