gurpreet singh
gurpreet singh

Reputation: 93

Scanf does not read user input as expected

The program is not taking inputs as it should. When I input t = 1 and l = 4 the inner loop takes only two inputs instead of four.

int main() {
  int l, b, g, count, t, i;
  char s[10000];
  scanf("%d%d", &t, &l);

  while (t--) {
    for (i = 0; i < l; i++) {
      scanf("%c", s[i]);
      if (i > 0)
        if (s[i] == s[i-1])
          count++;
    }
    printf("%d\n", count);
  }
  getch();      
}

Upvotes: 0

Views: 1504

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

The problem is that when you enter a character for any scanf, you press the enter key. The input(if valid) is consumed by the scanf and the newline character(since you pressed the enter key) stays in the standard input stream(stdin). When scanf(with %c) is called the next time, it sees the \n character in the stdin and consumes it, and thus does not wait for further input.

To fix it, Change

scanf("%c",s[i]);

To

scanf(" %c",&s[i]);

The space before the %c instructs scanf to scan any number of whitespace characters including none, until the first non-whitespace character. Quoting the standard:

7.21.6.2 The fscanf function

[...]

  1. A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.

scanf with the %c format specifier expects a char* or in other words, the address of a char. You provide the argument s[i] which is of type char. This invokes Undefined behavior. & is the address of operator, and it, when used before s[i], gives the address of s[i], which is a char*.

Upvotes: 3

user2736738
user2736738

Reputation: 30936

int main(){

    int  l,b,g,count,t,i;
    char s[10000];
    scanf("%d%d",&t,&l);
    getchar();
    while(t--){
         for(i=0;i<l;i++){
               scanf("%c",s[i]);
                      if(i>0)
                         if(s[i]==s[i-1])
                              count++;

               }
     printf("%d\n",count);

     }

     getch();      
    }

The two getchars are used to clear the '\n' that is there in the input buffer. The dummy getchars are just taking those extra '\n' and that will solve the problem.

Upvotes: 0

Related Questions