C++输入验证以确保输入的是数字而不是字母

标签 c++ validation while-loop

所以我正在尝试设置此程序来计算帐户余额。我需要确保起始余额输入为正数。我有正数部分,但如何确保输入也是数字而不是字母或其他非数字?

#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's deposits
        deposit2,    // Second month's deposits
        deposit3,    // Third month's 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() .

关于C++输入验证以确保输入的是数字而不是字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258831/

相关文章:

c++ - 模拟窗口之间的鼠标选择消息

php - 验证应该在 Form 对象或模型中完成吗?

javascript - 即使验证失败,表单仍在提交

python - 替换 Python 中的深度循环

php - 如何在 php 中添加 while 循环创建的图像的链接?

c++ - C/C++ 关于跟踪编程技术的问题

c++ - 编译时链接错误故障排除

c++ - 检测草图像中的植物

validation - AlertDialog中的TextFormField无法验证

sql - 如何在 sql server 2008 中进行双循环