1

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Hele
  • 23
  • 3
  • 4
    [___DO NOT___ use `gets()`, it is dangerous. use `fgets()` instead.](https://stackoverflow.com/a/41383540/2173917) – Sourav Ghosh Mar 15 '18 at 06:37
  • 2
    How would you say that 0 is skipped? What is the expected behavior, what is the observed behavior? – harper Mar 15 '18 at 06:39
  • If you use the C tag, it is assumed that you program in standard C. But this code cannot compile as standard C because it is too old. Therefore you need to add an extra tag corresponding to the dinosaur version of C that you are for some reason using, such as C90 or C99. – Lundin Mar 15 '18 at 09:16
  • Also make sure to burn the book or teacher that told you to use gets, then get a new one. – Lundin Mar 15 '18 at 09:17

2 Answers2

1

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.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
0

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189