如何让cin只接受用户输入的数字?

时间:2017-01-26 05:20:15

标签: c++ input error-handling numbers cin

因此,该程序的要求是能够增加相同大小的数组(大小从5到15个索引),并使用for和while循环将数组中的每个元素递增1。最后一项任务是从第一个数组中获取值,并将它们按相反的顺序排列,并将它们分配给第二个数组。

所以一切正常,程序拒绝无效输入,不会进入无限循环。但是,该程序接受一些不需要的输入。

例如,I would input something like '12 a'或'7 asdfkla; j lasnfg jasklgn asfg',它会通过。这也很有趣,因为代码只注册了12或7,完全忽略了其余部分。我认为这是因为一旦它遇到一个非整数字符,就会停止忽略其余部分。

为什么忽略输入的其余部分?有没有办法通过这个方法来捕捉这个错误?

此外,如果你看到任何引起你注意的事情,请随意批评c:我一直在寻求改进。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
    srand(time(NULL));
    int x;
    int j = 0;
    bool not_valid = true;

    system("color f");

    cout << "Program will ask for an input for the size of an array.\n"
         << "With the array size defined, program will generate semi-\n"
         << "true random integers from 0 to 8. First array will then\n"
         << "be assigned to the second in reverse (descending) order.\n\n";

    do {
        cout << "Enter array size (0 - 15): ";
        cin >> x;

        if (x >= 5 && x <= 15) {
            not_valid = false;
            cout << "\nArray size: " << x << endl;
        }
        else {
            cout << "Invalid input.\n\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }

    } while (not_valid);

    int *arr0;
    int *arr1; 
    arr0 = new int[x];
    arr1 = new int[x];

    for (int i = 0; i < x; i++) {
        arr0[i] = rand() % 9;
    }

    for (int i = 0; i < x; i++) {
        arr1[i] = rand() % 9;
    }

    cout << "\nARRAY 0 (unmodified, for):\n";
    for (int i = 0; i < x; i++) {
        cout << arr0[i] << "\t";
    }

    cout << "\n\nARRAY 0 (modified, for):\n";
    for (int i = 0; i < x; i++) {
        arr0[i]++;
        cout << arr0[i] << "\t";
    }

    cout << "\n\nARRAY 1 (unmodified, while):\n";
    for (int i = 0; i < x; i++) {
        cout << arr1[i] << "\t";
    }

    cout << "\n\nARRAY 1 (modified, while):\n";
    while (j < x) {
        arr1[j]++;
        cout << arr1[j] << "\t";
        j++;
    }

    int second = x - 1;

    for (int i = 0; i < x; i++) {
        arr1[second] = arr0[i];
        second--;
    }

    j = 0;
    cout << "\n\nARRAY 1 (array 0, descending):\n";
    while (j < x) {
        cout << arr1[j] << "\t";
        j++;
    }

    cout << endl << endl;
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

输入字符串中的输入,然后检查它是否为数字。

  

示例:

#include<iostream>
#include<sstream>
#include <string>
using namespace std;

int main()
{
    string line;
    int n;
    bool flag=true;
    do
    {
        cout << "Input: ";
        getline(cin, line);
        stringstream ss(line);
        if (ss >> n)
        {
            if (ss.eof())
            {
                flag = false;
            }
            else
            {
                cout << "Invalid Input." << endl;
            }
        }
    }while (flag);
    cout << "Yo did it !";
}