ghoshsai5000's blog

By ghoshsai5000, history, 7 years ago, In English

I was working on the problem Anton and Chess, and I have noticed that the entire output never gets read. Here is the code which deals with input — The input loop doesn't run as many times as it's supposed to and always takes one input less. This problem disappears if the character input line is removed.

#include <stdio.h>
#include <stdlib.h>

void get_piece_coordinates(char *, long *, long *, unsigned int);

int main()
{

        unsigned int no_of_black_pieces;
        long king_x_coordinate, king_y_coordinate;

         scanf("%u", &no_of_black_pieces);
         scanf("%lu %lu",&king_x_coordinate, &king_y_coordinate);

         long *x_coordinate = malloc(no_of_black_pieces*sizeof(long));
        long *y_coordinate= malloc(no_of_black_pieces*sizeof(long));
       char *piece= malloc(no_of_black_pieces *sizeof(char));

        get_piece_coordinates(piece, x_coordinate,y_coordinate,no_of_black_pieces);

       free(piece);
       free(x_coordinate);
       free(y_coordinate);
       return 0;
  }

  void get_piece_coordinates(char *piece, long *x_coordinate, long *y_coordinate, unsigned int no_of_black_pieces)
 {
      unsigned int i;

       for(i = 0; i < no_of_black_pieces ; i++)
      {

            scanf("%c",(piece + i));
             scanf("%lu %lu", (x_coordinate + i), (y_coordinate+ i));
       }
  }
  • Vote: I like it
  • +8
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Perhaps you should use " %c" instead of %c to skip the whitespace before the character you actually want to read.

  • »
    »
    7 years ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    Thanks. The problem got sorted. Can you explain what the problem was and why putting a space there fixed it ?

    • »
      »
      »
      7 years ago, # ^ |
        Vote: I like it +8 Vote: I do not like it

      That's how scanf works. It treats space as a character, using " %c" makes it ignore whitespace. Next time, trying using google before asking here.

      • »
        »
        »
        »
        7 years ago, # ^ |
          Vote: I like it +8 Vote: I do not like it

        I did use Google, but I googled the question of this thread. I thought the problem was with the pointer of array of characters not with how a character was read.