-2

Who does the following program take 10 inputs instead of 9?

#include <stdio.h>

int main()
{
    int arr[3][3];

    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            scanf("%d ", &arr[j][i]);


    printf("\n");

    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            printf("\n%d ", arr[j][i]);
    

     return 0;
}

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39

1 Answers1

1

A space character in a format string tells scanf to read and discard white space characters (including spaces, tabs, and new-line characters) until a non-white-space character (or end of stream or error) is seen. So, after reading a number, scanf("%d ") continues reading. If you pressed Enter/Return after entering a number, scanf reads the new-line character that generated. Then it reads the next character. Only when you enter a non-white-space character, such as a digit, does it stop.

Remove the space from the scanf string. %d already includes reading and ignoring white-space characters before the number, so another space is not needed in the string.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Actually the space should be before the %d to discard leading whitespace. – Alex Nicolaou Mar 08 '22 at 19:40
  • @AlexNicolaou: No, it should not. Leading white-space characters are already discarded, per C 2018 7.21.6.2 8, which discusses the first step of execution a conversion specification (a `scanf` directive starting with `%`): “Input white-space characters (as specified by the `isspace` function) are skipped, unless the specification includes a `[`, `c`, or `n` specifier.” – Eric Postpischil Mar 08 '22 at 20:16
  • You're right, I was thinking of `%c`. – Alex Nicolaou Mar 08 '22 at 20:18