Printf statement getting skipped in Numbers

Hey, this is regarding the problem, NUMBERS which came in the Lunch Time competition. To check my code, I put a few printf statements in my code. But somehow, the printf statement for the strings, marked on line 42, isn’t getting printed. Can someone please suggest why?

My Code: IXMS7v - Online C Compiler & Debugging Tool - Ideone.com
Error: alt text

Problem : NUMBERS Problem - CodeChef

1 Like

Problems seems to be with your input method

instead of " fgets(player[i].name, 2, stdin); “,use “scanf(”%s”,player[i].name);"

The thing is that stdout (the file-stream printf() is writing to) is line buffered. This means that the output is deferred from printing until a ‘\n’ is encountered.

There are two ways you can get the output from printf(). Either flush the buffer explicitly using fflush(stdout) or prevent buffering all together using setbuff(stdout, NULL)

Okay this did, solve the problem, but I don’t get it why I should use scanf instead of fgets. Isn’t fgets supposed to be better? I’ve read that its “safer”.

Where exactly should I use fflush()? I tried putting it before the print statement, but it didn’t help.
Btw, how does scanf solve the problem?

I went through your code and I am afraid its pretty messed up. The way you are using fgets() is not proper. I think you are forgetting that fgets() reads ‘\n’ also(unlike scanf())and does not read further when it encounters one. Thus, some of your ‘name’ fields are just newlines and scanf() is failing as it is being made to read text.

Please note that fgets() is generally used to read one line of input at a time. Do not use both scanf() and fgets() in reading a single line of input if you are not an expert.

1 Like