Hele
Hele

Reputation: 23

Initialized variable skips 0 during for loop

This is a simple version of my code that still doesn't work when I run it. When I initialize i to be the counter for my for loop, it skips 0 for some reason, this has never happened to me before and I don't know why.

#include <stdio.h>
#include <string.h>

int main() {
    int x, i;
    scanf("%d", &x);
    char array[x][10];
    for (i = 0; i < x; i++) {
        printf("%d\n", i);
        gets(array[i]);
    }
    return 0;
}

edit: I input 5 for x, therefore I would have a character array size 5 rows, 10 columns. For i, it is supposed to start at 0, so I input array[0] first but skips to 1, so I start my input with array[1], that means my first row has no input.

Upvotes: 1

Views: 82

Answers (2)

chqrlie
chqrlie

Reputation: 144695

scanf() only consumes the characters that make up the converted number. Any remaining input, especially the newline that you typed after 5 is left in the input stream.

The for loop does start at 0, and 0 must be output by your program, but gets() reads the pending input upto and including the newline, so the next iteration comes immediately: 1 is output and the program only then waits for input.

Note that you must not use obsolete function gets() because it cannot determine the maximum number of characters to store to the destination array, so undefined behavior on invalid input cannot be avoided. Use fgets() or getchar() instead.

Here is how to fix your program:

#include <stdio.h>
#include <string.h>

int main() {
    int x, i, j, c;
    if (scanf("%d", &x) != 1)
        return 1;
    while ((c = getchar()) != EOF && c != '\n')
        continue;
    char array[x][10];
    for (i = 0; i < x; i++) {
        printf("%d\n", i);
        for (j = 0; (c = getchar()) != EOF && c != '\n';) {
            if (j < 9)
                array[i][j++] = c;
        }
        array[i][j] = '\0';
    }
    return 0;
}

Upvotes: 0

Stephen Docy
Stephen Docy

Reputation: 4788

scanf() leaves some characters in the input stream, which are picked up by the first call to gets(), causing the first gets() to finish immediately and the program to continue and prompt for the input for array[1], hence "skipping" over 0.

Upvotes: 1

Related Questions