Help me out with fread()

Whats wrong with the code it’s giving WA ?
https://www.codechef.com/problems/INTEST

#include<bits/stdc++.h>
using namespace std;

int main(){

#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

int n, num = 0, k, count = 0;
char buf[30000];
scanf("%d %d", &n, &k);
//int charRead = fread(buf, 1, 30000, stdin);
int t = 0;
while(t < n){
int charRead = fread(buf, 1, 30000, stdin);
for(int i=0; i<charRead; i++){
	if(buf[i] == '\n'){
	    t++;
		if(num%k == 0) count++;
		num = 0;
	}
	else{
	    num = num*10 + (buf[i] - '0');
	}
}
}
printf("%d\n", count-1);
return 0;

}

2 Likes

As WA verdict depends on the question so you must also post the problem link.

1 Like

sorry , just edited the post with the link!

1 Like

Guesses as to what is going wrong:

  1. Possibly the test input uses uses windows line endings (containing a \r) - I don’t know whether C’s input will auto-convert for you. I think this might be the least likely explanation.
  2. There’s a flaw in that, because you don’t consume the carriage return from the first line (the one with n and k on it), the first integer “read” is always 0, which eats up one of your n's and which is divisible by k (which is why you are subtracting one from count before you print it!)
    Now, if the final number is not fully contained in the current buffer after reading the second-to-final number, then the loop will finish without ever reading the final number (because the spurious 0 read at the beginning eats up one of your n's), which will give the wrong answer if this final number is divisible by k.

Edit:

The results might vary from platform to platform, but I think this exemplifies the problem - it has 2728 copies of the number 1000000000 (divisible by k = 4), but on my machine at least, your program gives the output 2727. It’s specifically tailored to break things if the buffer size is 30000.

1 Like

You just have to check how many elements of array are divisible by k.

1 Like