Confusion over scanf and getchar()

Well I was solving Buy1-Get1 from the practice problems(easy) and came across something strange

My code would get accepted if i took the string input as follows and then did the neccessary operations:



         arr[(int)str[i]]++;           // arr is just another array

But instead i was trying to take the input as follows and was doing the necessary operations:

----->NOTE:In the prob the user enters \n after giving number of testcases and i took the input as scanf("d*c",&t) so as to account for the ‘\n’ entered <-----



My code wouldn’t get accepted and gave WA for the below version.(the remaining code didn’t change for the two versions…)

Can someone please tell me whats wrong?

Thanks for the help!!! :slight_smile:

@hitesh96db: There are two errors in ur code.

     i) when reading t use \n to denote the newliine character after the integer.

    ii) when checking (c=getchar()!='\n') add the condition  (c!=EOF) because there is no '\n' character after the last testcase. to the working solution.
    hope this helps u :)
1 Like