if (isalpha(donation[index])) <-- no good, it's too late for that. You have a 'double' variable (array slot), so you can't meaningfully check if it's alphabetic. What this is going to do is implicitly convert that double to int (by rounding), and then check whether the value of that int is in the ASCII range where the letters live (65-90 and 97-122, inclusive). o_O
You *do* want to check the input for failure, and skip over the bad input, just don't loop to insist on a new value:
if(!(cin >> donation[index])) { // Oops, there's something at the beginning of the input stream // which can't be interpreted as a double. // First, make cin "recover" so that we can read more data cin.clear(); // Skip past the garbage data, until a new line cin.ignore(std::numeric_limits<INT_MAX>, '\n'); // <-- I think that's right... // "Cancel the input" as you say donation[index] = 0; // In this case, the poster telling you to initialize the array // is not on the right track; with this setup, something valid // will get written to each array element.}
However, there's another logical problem with how you "cancel the input": the int "wrong" can only remember one "invalid" location. Also, "size" wants to count the valid entries - but even if the "wrong" setup worked, "size" gets set to one plus *the last valid entry*. You want to *increment* it for each valid entry. :/
Here's how I'd do it, in pseudocode. Translation is left as an exercise :)
size = 0repeat 10 times: try to assign input to donation[size] if successful: size = size + 1 otherwise: recover cin and ignore the input # there is no longer a need for a "wrong" variable# After every iteration of the loop, "size" points at the first# slot that hasn't been written to yet, so you won't overwrite# things or skip array slots. It's also equal to the number of# assigned slots, so after the loop, it tells you how many slots# are assigned. This is why 0-based indexing is a Good Thing :)sum = 0# So now, we need to loop size-many times, to grab all the# assigned values, and add them up:repeat with i from 0 to (size - 1): sum = sum + donation# and now that we have the sum, and number of elements,# getting the average is easy:print (sum / size)
P.S. Give variables names that describe their actual contents. Don't call something "average" if it's the sum. Call it "sum". I know your goal is to find the average, but you'll confuse yourself (and maybe forget to divide by number of elements?) that way... once you're doing more serious stuff, it's bound to happen... trust me. :)