Couldful Rial
Couldful Rial

Reputation: 3

C: Ask for inputs as an array

I would like to ask user's input to form an integer array. And if one input gets invalid, which is not integer, the current array will be printed and ask the user to continue entering numbers from the last position. This is my code, but it is not working. What should I do?

int A[SIZE], i;

    for (i=0; i<SIZE; i++) {
        A[i] = 0;
    }

    printf("Enter %d numbers as an array: ", SIZE);
    i = 0; // Initialize i
    while (i<SIZE) {
        for (i=i; i<SIZE; i++) {
            if (!scanf("%d", &A[i])) {
                printf("Invalid input!\n");
                printarray(A, SIZE);
                printf("i = %d", i);
                break;
            } 
        }
    }

Upvotes: 0

Views: 58

Answers (1)

Emanuel P
Emanuel P

Reputation: 1576

If the user enters something other than an integer, scanf will continue failing because the input is still there. One way to solve this is reading line by line using fgets and then using sscanf to scan the line for a number. You also should only increase i if the input is valid.

Combined with the other comments, you can get something like this:

int i=0;
while(i<SIZE)
{
    char line[100];
    fgets(line, sizeof line, stdin);
    if(sscanf(line, "%d", &A[i]) == 1)
        ++i;
    else
    {
        printf("Invalid input!\n");
        printArray(A, i);
        printf("i = %d", i);
    }
}

You should add error handling for fgets and sscanf. fgets returns NULL on error and sscanf returns EOF on an error.

Upvotes: 1

Related Questions