Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate the input of an array?

How do I validate input for the array to only accept integers?

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

int main()
{
    int TheNumbers[10];// An array of 10 indexes 
    int i;

    for (i=0; i<10; i++) // accepts input 10 times
    {
        cout << "Enter a number: ";
        cin >> TheNumbers[i];
    }
    
    for (i=9; i>=0; i--) // returns inputs in reverse order
    {
        cout << TheNumbers[i] << endl;
    }
        
    // ERROR MSSG: While input is not an integer
    while(!(cin >> TheNumbers[10]))
    {
        cout << "**Inncorect input** \n" << "Please input a number: \n";
        cin.clear();
        cin.ignore(50, '\n');
    }

    return 0;
}
Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: 32765
-882742640
22081
1189945728
0
0
22081
1189946384
32744
0

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could try adding another nested loop:

static const int MAXIMUM_NUMBERS = 10;
//...
for (int i = 0; i < MAXIMUM_NUMBERS; ++i)
{
    std::cout << "Enter a number: ";
    while (!(cin >> number[i]))
    {
        std::cout << "Invalid number.  Try again.\n";
        std::cout << "Enter a number: ";
        std::cin.clear(); // Clear the error.
        std::cin.ignore(10000, '\n');
    }
}

This is a simple example, there are other methods.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading