scanf “extra input” required

前端 未结 3 2146
遇见更好的自我
遇见更好的自我 2021-01-14 01:48

for some simple HW code I wrote I needed to get 7 arguments via the scanf function:

scanf(\"%d %d %d %d\\n\", &vodka, &country, &life, &glut)         


        
3条回答
  •  深忆病人
    2021-01-14 02:27

    White space characters in the scanf format string are directives that mean read white space characters until you get a non white space character. A trailing \n in your format string causes scanf to consume the linefeed that was typed by the user and to keep asking for input until a non white space character is seen, but is left in the input buffer.

    To consume the \n exactly, you can use this ugly scanf format:

    scanf("%d%*1[\n]", &mprice);
    

    Or you can just remove the trailing \n and consume the character with getchar() but be aware that neither of these approaches provide for exact matching of the input:

    scanf("%d", &mprice);
    getchar();
    

提交回复
热议问题