I\'m doing an exercise in C but I have a problem when at the and I want to repeat the cicle (do while), infact if I type 1 the programme starts again by the top, but it doesn\'t
It's because the scanf
call at the end of the loop doesn't read the newline. Instead this newline is read by your gets
call.
A simple solution is to add a space to the end of the scanf
format string, like so:
scanf("%d ", &j);
This will make scanf
skip trailing whitespace in the input.
Another solution is to put an extra fgets
after the scanf
, but then don't add the extra space in the format string:
scanf("%d", &j);
fgets(testo, sizeof(testo), stdin);
Or use fgets
to get the line, and then use sscanf
to extract the answer:
fgets(testo, sizeof(testo), stdin);
sscanf(testo, "%d", &j);