How do you allow spaces to be entered using scanf?

前端 未结 11 1682
我寻月下人不归
我寻月下人不归 2020-11-21 06:05

Using the following code:

char *name = malloc(sizeof(char) + 256); 

printf(\"What is your name? \");
scanf(\"%s\", name);

printf(\"Hello %s. Nice to meet y         


        
11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 06:36

    Don't use scanf() to read strings without specifying a field width. You should also check the return values for errors:

    #include 
    
    #define NAME_MAX    80
    #define NAME_MAX_S "80"
    
    int main(void)
    {
        static char name[NAME_MAX + 1]; // + 1 because of null
        if(scanf("%" NAME_MAX_S "[^\n]", name) != 1)
        {
            fputs("io error or premature end of line\n", stderr);
            return 1;
        }
    
        printf("Hello %s. Nice to meet you.\n", name);
    }
    

    Alternatively, use fgets():

    #include 
    
    #define NAME_MAX 80
    
    int main(void)
    {
        static char name[NAME_MAX + 2]; // + 2 because of newline and null
        if(!fgets(name, sizeof(name), stdin))
        {
            fputs("io error\n", stderr);
            return 1;
        }
    
        // don't print newline
        printf("Hello %.*s. Nice to meet you.\n", strlen(name) - 1, name);
    }
    

提交回复
热议问题