1

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 );
}
4
  • Why don't you input as a string, then check if the string is a valid number. Commented Feb 21, 2013 at 22:37
  • The function prototype has to be the same as the professor's. Commented Feb 21, 2013 at 22:39
  • possible duplicate of The Definitive C++ Book Guide and List Commented Feb 21, 2013 at 22:42
  • well, you could iterate through array for the value of i or utilize try and catch in some way. Since it is homework, I do not want to be specific. Commented Feb 21, 2013 at 22:42

2 Answers 2

2

Like this:

if (!(cin >> a[i])) { die("boo"); }
Sign up to request clarification or add additional context in comments.

5 Comments

What if the input was zero?
Well, zero is a valid input, isn't it? (It is an unsigned integer)
Ok, I was just checking. I've used (!(statement)) in the past but may be unsure of exactly what it means. I thought it meant "if input was zero." Is that wrong? Thanks for the help.
@user1681673: The result of cin >> a[i] is the stream object, not the integer. So you're testing whether the stream has failed. Only if the stream is still good are you even allowed to touch the integer.
OH. So it's checking whether or not a stream occurred. Got it. Thanks for the help.
0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.