Search code examples
cloopswhile-loopscanfinfinite

while(scanf) is infinite looping?


The code is supposed to accept a line of user input containing different characters and then print out one line containing only the letters. For example, Cat8h08er64832&*^ine would be Catherine. However, the code works and outputs "Catherine" however the program doesn't exit... see picture here I'm not sure if the loop is just looping infinitely or...

int main(void){

  int i=0, j=0;
  char userString[1000];
  char alphabet[1000];

  printf("Please enter a string: ");

  while(scanf("%c", &userString[i])){
    if((userString[i]>='A' && userString[i]<='Z')||(userString[i]>='a'&&userString[i]<='z')){
        alphabet[j]=userString[i];
        printf("%c", alphabet[j]);
        j++;
     }
     i++;
   }
   printf("\n");
   return 0;
}

Solution

  • Your problem is that you're checking that scanf is finished by checking for the return value 0. scanf returns EOF (usually, -1) when there is no more input. So if you get some input (return 1) then no more input (return -1), your loop won't ever exit.

    Change the scanf condition to check for <> EOF.

    This answer also explains it quite well.