Difference in answer in online and offline compiler

link :

https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/nice-arches-1/

link to solution :

My code passes some test cases online but fails on others.

But when i tried failed cases on my compiler(offline) it shows correct answer .

So why it is showing WA on online complier while correct on codeblocks ide???

1 Like

Seems like there is some issue due to your input method:

After
cin >>a
when you input a and enter, there is also a \n character left by cin, therefore, when you use cin.getline() or gets(str) it will read that newline character.

cin >>a;

cin.ignore(); //this is necessary

gets(str);

Here’s your accepted Solution wit the above fix. Code on HackerEarth

Hope it helped. :smiley:

2 Likes

@chunky_2808
Now, the thing is FFLUSH:
fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file. But eventually, YOU’RE USING IT ON INPUT STREAM. Simply, what you’re doing above is undefined behavior of fflush function. If you read more about fflush on C documentation you’ll find out that fflush is meant to be called on an output stream.
Hope that helps you…

int fflush(FILE *ostream);
ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

@ssaxena36 .Yes, i guess i have observed it too but compilers like g++ allows this to clear buffer from input. I am saying this because fflush has always worked in case in we use it in Codeblocks or similar IDE,but not in LINUX.

Thanks for the information :slight_smile:

Your approach worked.
But why is fflush not working??? Because that is the purpose of using fflush(stdin) to buffer out all garbage .

1 Like

And also then why are some test cases working.
if that is the problem it should have shown WA for all the testcases.

ok thanks!!

1 Like