使用Ints和Doubles进行输入验证

时间:2015-06-25 09:39:38

标签: c++ c++11

所以我试图让用户在选择数组大小时只接收整数,但如果我要键入浮点数,则数字不会相加。如果他们输入字母然后弹出正确的错误信息,但如果他们按照我目前的方式输入4.4,1.21等,我就无法做到。我这么努力吗?我会更好地使用stringstream吗?我遗漏了一大堆代码。

#include <iostream>
#include <limits>


int main()
{
const int CAPACITY = 100;
int choice;
int size = 0;
double array[CAPACITY];

    do
    {
    std::cout << "Hey there! Pick an option" << std::endl;
    std::cout << "Hit 1 to do some math " << std::endl;
    std::cout << "Hit 2 to quit" << std::endl;
    std::cin >> choice;

    if (choice == 1)
    {

        std::cout << "Choose the size of your array. The array can be set to capacity of 100" << std::endl;
        //std::cin >> size;

        if((std::cin >> size).fail()) {
            std::cin.clear();
            std::cin.ignore(1000, '\n');
                std::cout << "Invalid input" << std::endl;
                continue;
            }
        if(size <= 0){
            std::cout << "Sorry, that not a valid option" << std::endl;
            continue;
        }
        if (size > CAPACITY){
            std::cout << "Sorry, that is too large" << std::endl;
            continue;
        }
        if (size < CAPACITY){
            std::cout << "Add some numbers to your array" << std::endl;

            for (int i=0; i < size; i++)
            {
                std::cout << "Enter a number: " << std::endl;
                std::cin >> array[i];
            }

1 个答案:

答案 0 :(得分:0)

如前所述std :: stringstream是这种情况下的解决方案

std::string s;
std::cin >> s;
std::stringstream ss(s);
int n;
// Only accept if stringstream is empty after parsing
if(! (ss >> n) || !ss.eof() )
 std::cerr << "something's fishy with '" << s << "'" << std::endl;