user1681673
user1681673

Reputation: 368

How to check if the input into an array failed?

I'm doing a homework assignment and one function I need to write is a simple function that allows the user to input an int that will go into an array. One of the conditions though is to check if the input failed, and if it did, end the the program with a 'die' function. How do I check if the input was not put into the array? Should I just check that the input was an int? Thanks for the help.

void input( unsigned a[], unsigned elements ){


    for (unsigned i = 0; i < elements; i++) {
        cout << "Enter a number for index #" << i <<" in the array:" << endl;
        cin >> a[i];
    }

    // Add die function if this function fails...

}

bool die(const string &msg) {
    cerr <<endl << "fatal error: " <<msg <<endl;
    exit( EXIT_FAILURE );
}

Upvotes: 1

Views: 236

Answers (2)

user2116846
user2116846

Reputation: 11

void input( unsigned a[], unsigned elements ) {

for (unsigned i = 0; i < elements; i++) {
    cout << "Enter a number for index #" << i <<" in the array:" << endl;
    cin >> a[i] || die("Error");
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477444

Like this:

if (!(cin >> a[i])) { die("boo"); }

Upvotes: 2

Related Questions