How do you allow spaces to be entered using scanf?

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

    While you really shouldn't use scanf() for this sort of thing, because there are much better calls such as gets() or getline(), it can be done:

    #include 
    
    char* scan_line(char* buffer, int buffer_size);
    
    char* scan_line(char* buffer, int buffer_size) {
       char* p = buffer;
       int count = 0;
       do {
           char c;
           scanf("%c", &c); // scan a single character
           // break on end of line, string terminating NUL, or end of file
           if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
               *p = 0;
               break;
           }
           *p++ = c; // add the valid character into the buffer
       } while (count < buffer_size - 1);  // don't overrun the buffer
       // ensure the string is null terminated
       buffer[buffer_size - 1] = 0;
       return buffer;
    }
    
    #define MAX_SCAN_LENGTH 1024
    
    int main()
    {
       char s[MAX_SCAN_LENGTH];
       printf("Enter a string: ");
       scan_line(s, MAX_SCAN_LENGTH);
       printf("got: \"%s\"\n\n", s);
       return 0;
    }
    

提交回复
热议问题