0

i have this function in my project:

void inputIntArray(int array[], int size){
j = size;
for(i=0;i<j;i++){
    printf("* Enter number #%d out of %d: ",(i+1),j);
    scanf("%d",&k);
    array[i] = k;
    }
}

It's supposed to fill an array, and works fine when integers are input, when something which is not an integer is being inputted it will just fill the remaining cells in the array with the last integer inputted and skip the whole project while only printing everything remaining...

Anyone knows what causes this error? Thanks!

EDIT: After changing to:

void inputIntArray(int array[], int size){
    int i = 0,j = 0,k = 0;
    j = size;
    for(i=0;i<j;i++){
        printf("* Enter number #%d out of %d: ",(i+1),j);
        if(scanf("%d",&k) != 1){
            break;
        }
        array[i] = k;
    }
}

I'm still experiencing the same error.....

1
  • 1
    The return value of scanf is the number of successfully read inputs. If you check that, you can act appropriately. You're expecting 1, if you don't get that, do something about it. Commented Nov 25, 2013 at 16:43

4 Answers 4

1

What do you expect it to do if a non-integer is used as the input? It doesn't seem like it's an error skipping non-integer input, but the correct behavior. If you want it to keep working, you need to handle that error by checking what the user inputs. If the input is not what the program expects, it's up to the coder to resolve that or you'll get unexpected behavior.

Sign up to request clarification or add additional context in comments.

Comments

1

Your error is the fact that your array is of type int. If you want some other type, you'll have to have an array of that type.

Comments

1

You need to check if scanf() fails. If it does, because invalid data was entered, you have to flush the stdin buffer and repeat the scanf() again.

Comments

0

The format specifier %d tells scanf to expect an integer. See e.g. here.

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.