Search code examples
carraysmallocskip

c array error, skips some elements


int main(int argc, char *argv[])

{

  int length,i,j;

  char *key;

  printf("\n\n\n   What is the length of key?\n");
  scanf("%d",&length);

  key=(char*)malloc (length*sizeof(char));

  for(i=0;i<length;i++)
  {
                      printf("\n Enter  %d. character ...\n",i+1);
                      scanf("%c",&key[i]);
 }

 getch();
  system("PAUSE");
  return 0;
}

When i execute, it asks

enter 1.character enter 2. character inputhere enter 3.char enter 4.char

It goes like that, it doesnot ask odd ones.Not only odd ones, if for example length is 7, it asks 4 and then 3 characters. Why can this be?


Solution

  • The %c conversion specifier won't skip over leading whitespace characters, so it's picking the newline character that's still in the input stream from the previous entry. IOW, suppose you type in a length of 10. The input stream then contains the characters '1'. '0', and '\n'. The first scanf("%d", &length) call consumes the '1' and the '0', but leaves the '\n' in the input stream. Thus, the first scanf("%c", &key[i]) reads the '\n' character, not the character you entered.

    The workaround for this is to add a blank space in the format string before the %c conversion specifier: scanf(" %c", &key[i]). This will tell scanf to skip over any learning whitespace and read the first non-whitespace character into key[i].