Strings, gets and do while

前端 未结 3 1193
遇见更好的自我
遇见更好的自我 2021-01-26 12:43

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

3条回答
  •  無奈伤痛
    2021-01-26 12:57

    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);
    

提交回复
热议问题