c - Scanf does not read user input as expected -


the program not taking inputs should. when input t = 1 , l = 4 inner loop takes 2 inputs instead of four.

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

the problem when enter character scanf, press enter key. input(if valid) consumed scanf , newline character(since pressed enter key) stays in standard input stream(stdin). when scanf(with %c) called next time, sees \n character in stdin , consumes it, , not wait further input.

to fix it, change

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

to

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

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

7.21.6.2 fscanf function

[...]

  1. a directive composed of white-space character(s) executed reading input first non-white-space character (which remains unread), or until no more characters can read. directive never fails.

scanf %c format specifier expects char* or in other words, address of char. provide argument s[i] of type char. invokes undefined behavior. & address of operator, , it, when used before s[i], gives address of s[i], char*.


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -