Why does scanf ask twice for input when there's a newline at the end of the format string?

后端 未结 6 993
野的像风
野的像风 2020-11-22 04:52
#include 
#include 
#include 

char *method1(void)
{
    static char a[4];
    scanf(\"%s\\n\", a);
    return a;
}

i         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 05:04

    you have to remove the \n from the string format of the scanf. It should be

    scanf("%s",a);
    

    EDIT: Explanation

    the %s means that the scanf reads the input character till it gets a delimiter which should be a white space like space or tab or new line(\n) so the first enter is get as a delimiter for the "%s" and adding the "\n" to the string format "%s\n" means that the scanf will wait 2 newlines the first newline is related to the delimiter of the "%s" and the second newline is related to the\n of the string format.

提交回复
热议问题