首页 > 解决方案 > 输入字母、符号和负数时验证年龄输入以提示消息

问题描述

我想用我在下面写的代码来验证输入年龄

cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
for (int i = 1; i <= qty; i++) {
    cout << "\nAge for Passenger " << i << " :: ";
    cin >> age[i];

    while ((!(cin >> age[i])) || (age[i]<=0)) {
        // Explain the error
        cout << "Error: Enter a valid age for Passenger " << i << " : ";
        // Clear the previous input
        cin.clear();
        // Discard previous input
        cin.ignore(123, '\n');
    }
}

但有个问题。当我输入范围内的年龄时,程序将停止运行。所以,我想问是否有任何有效的方法来验证年龄输入。

标签: c++visual-c++

解决方案


考虑使用std::getlinestd::stringsstream。因此,您只是在阅读行,然后尝试对其进行解析。

例如:

#include <iostream>
#include <sstream>

int main(int argc, const char * argv[])
{
    int qty = 10;
    int* age = new int[11];
    std::cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
    for (int i = 1; i <= qty; i++) {
        std::cout << "\nAge for Passenger " << i << " :: ";
        std::string s;
        std::getline(std::cin, s);
        std::stringstream stream(s);

        while ((!(stream >> age[i])) || (age[i]<=0)) {
            // Explain the error
            std::cout << "Error: Enter a valid age for Passenger " << i << " : ";
            std::getline(std::cin, s);
            stream = std::stringstream (s);
        }
    }

    for (int i = 1; i <= qty; i++) {
        std::cout << age[i];
    }

    delete [] age;
    return 0;
}

另请注意,using namespace std从 1 开始使用和索引是不好的模式


推荐阅读