How do you allow spaces to be entered using scanf?

前端 未结 11 1683
我寻月下人不归
我寻月下人不归 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:17

    You can use this

    char name[20];
    scanf("%20[^\n]", name);
    

    Or this

    void getText(char *message, char *variable, int size){
        printf("\n %s: ", message);
        fgets(variable, sizeof(char) * size, stdin);
        sscanf(variable, "%[^\n]", variable);
    }
    
    char name[20];
    getText("Your name", name, 20);
    

    DEMO

提交回复
热议问题