Поэтому я пытаюсь настроить эту программу для расчета баланса учетной записи. Мне нужно убедиться, что начальный баланс введен как положительное число. У меня есть положительная часть вниз, но как я могу убедиться, что ввод также является числом, а не буквами или другими не номерами?
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double startBal, // Starting balance of the savings account
ratePercent, // Annual percentage interest rate on account
rateAnnual, // Annual decimal interest rate on account
rateMonth, // Monthly decimal interest rate on account
deposit1, // First month deposits
deposit2, // Second month deposits
deposit3, // Third month deposits
interest1, // Interest earned after first month
interest2, // Interest earned after second month
interest3, // Interest earned after third month
count; // Count the iterations
// Get the starting balance for the account.
cout << "What is the starting balance of the account?" << endl;
cin >> startBal;
while (startBal < 0 ) {
cout << "Input must be a positive number. Please enter a valid number." << endl;
cin >> startBal;
}
// Get the annual percentage rate.
cout << "What is the annual interest rate in percentage form?" << endl;
cin >> ratePercent;
// Calculate the annual decimal rate for the account.
rateAnnual = ratePercent / 100;
// Calculate the monthly decimal rate for the account.
rateMonth = rateAnnual / 12;
while (count = 1; count <= 3; count++)
{
}
return 0;
}
Благодарю!!!
Вы можете проверить, успешно ли cin
:
double startBal;
while (!(std::cin >> startBal)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
std::cout << "Enter a valid number\n";
}
std::cout << startBal << endl;
Не забудьте #include <limits>
для использования std::numeric_limits<streamsize>::max()
.
double x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
Замените x
и double
любое имя и тип переменной, которые вам нужны. И, очевидно, измените свои подсказки на все, что необходимо.
То, о чем вы просите, на самом деле довольно сложно. Единственный совершенно правильный способ - прочитать свой ввод в виде строки, а затем посмотреть, соответствует ли строка правильному формату для числа, и только затем преобразовать строку в число. Я думаю, что это довольно сложно, когда вы просто новичок.
10000
наnumeric_limits<streamsize>::max()