Я немного новичок в C++ и был бы очень признателен за любые предложения или предложения! Итак, с нашими проектами интро-курса я искал способ убедиться, что когда прог. запрашивает значения int, которые он правильно отвечает! То есть он заявляет, что он недействителен в случаях как двойной, так и вводимой строки! Поэтому, если cin >> intVariable ... intVariable не примет запись cin «abdf» или 20.01.C++ Обеспечение того, чтобы пользовательское значение вводилось только int
Чтобы достичь этого, я написал следующую функцию ... Он работает, но я ищу ваши мысли о том, как этот процесс может быть дополнительно улучшен!
void getIntegerOnly(int& intVariable, string coutStatement)
{
bool isInteger; // Check if value entered by user is int form or not
string tmpValue; // Variable to store temp value enetered by user
cout << coutStatement; // Output the msg for the cin statement
do
{
cin >> tmpValue; // Ask user to input their value
try // Use try to catch any exception caused by what user enetered
{
/* Ex. if user enters 20.01 then the if statement converts the
string to a form of int anf float to compare. that is int value
will be 20 and float will be 20.01. And if values do not match
then user input is not integer else it is. Keep looping untill
user enters a proper int value. Exception is 20 = 20.00 */
if (stoi(tmpValue) != stof(tmpValue))
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
else
{
isInteger = true; //Set to true!
clear_cin(); // Clear cin to ignore all text and space in cin!
}
}
catch (...) // If the exception is trigured!
{
isInteger = false; // Set to false!
clear_response(); // Clear response to state invalid
}
} while (!isInteger); //Request user to input untill int clause met
//Store the int value to the variable passed by reference
intVariable = stoi(tmpValue);
}
Это просто пример получения пользователей возраст и возраст больше нуля при запуске приложения на основе Win32 на консоли! Спасибо за обратную связь :)
Вы можете найти строку для '.' персонаж. – mbadawi23
Пожалуйста, не могли бы вы сменить свой тег C++ на C++ 11, если вы это используете? – ha9u63ar
За исключением того факта, что пользователю может быть 3000+ лет, ваш код должен быть в порядке. –