Statement is being printed twice | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Statement is being printed twice

I wrote code to make a number guessing game in c. The code takes input and if you guess correctly asks you if want to play again. The bug I'm facing is the prompt statement (line 41 and 42) asking if you would like to play again are being printed twice instead of once (the output on sololearn is correct. It prints the prompt statement twice even in a text editor/ IDE). The numbers you are to enter to win the game are commented on the first line of main() in the code. If you run the code on sololearn, both mobile and web, your input will look like this: ''384 n'' The number part is the number you guessed and "n" is the answer to line 41 and 42, if you would like to immediately end the program and view the bug if not enter 'y' after the '384' and keep entering the numbers commented in main alternating it with the letter 'y' . On sololearn do include a line break between the number and "y / n". https://code.sololearn.com/cCLV7LyeEUkB/?ref=app

15th Dec 2021, 2:36 AM
Segmentation Fault
Segmentation Fault - avatar
1 Answer
+ 2
When the program reads number with scanf("%d", &number) it leaves the newline '\n' in the input buffer for the next time it reads. So upon reaching yesOrNo = getchar() it gets '\n' instead of 'y' or 'n'. The program logic takes no further action due to the invalid input, and it loops again to the yesOrNo = getchar(). This time it gets 'n' and properly exits. There is a simple fix. Change the format specifier from "%d" to "%d\n" so that will it parse out the newline and move past it: scanf("%d\n", &number); Remember to do this in all the places that read number.
15th Dec 2021, 8:43 AM
Brian
Brian - avatar