Блог пользователя ghoshsai5000

Автор ghoshsai5000, история, 8 лет назад, По-английски

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));
       }
  }
  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +8 Проголосовать: не нравится

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

    • »
      »
      »
      8 лет назад, # ^ |
        Проголосовать: нравится +8 Проголосовать: не нравится

      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.

      • »
        »
        »
        »
        8 лет назад, # ^ |
          Проголосовать: нравится +8 Проголосовать: не нравится

        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.