tricoder
tricoder

Reputation: 95

unexpected behavior of while loop variable with scanf reading string

Value of n changes abruptly in this below code when i am including scanf to read string. i also tried %*c but its still showing the same error.

 #include<stdio.h>
 #include<string.h>

 int main()
 {
  char str[3];
   int n;
   int t,p=0;
   scanf("%d",&t);

   while(t--)
    {
      printf("t=%d ",t);
      scanf("%d",&n);
       while(n!=0)
        {
          printf("n=%d",n);
          p=0;   
          scanf("%s",str);
          getchar();
          if(strcmp(str,"lhx")==0)
          printf("lhx");
          else
          printf("hhb");
          n--;
         }
      }
     return 0;
  }

Upvotes: 1

Views: 75

Answers (2)

Gopi
Gopi

Reputation: 19874

The issue is your array can hold just 3 characters

char str[3];

So 2 valid characters followed by a null terminator but you check it against a string with 3 characters.

So change your array to

char str[4];

scanning a string using scanf() is always a bad idea use fgets() instead.

Upvotes: 1

P.P
P.P

Reputation: 121427

Judging by if(strcmp(str,"lhx")==0), you are inputting 3 characters. But str has memory for only 3 characters. To scanf it as a string, you'll need at least 4 bytes of memory for str.

You could fix by changing it to:

  char str[4];

But then again, you'll have the same problem when you input 4 characcters. Use fgets instead of scanf(). fgets() will protect against buffer overflow.

Aside: use a standard signature for main(): int main(void) or int main(int argc, char**argv) or its equivalent.

Upvotes: 1

Related Questions