How do you allow spaces to be entered using scanf?

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

    You may use scanf for this purpose with a little trick. Actually, you should allow user input until user hits Enter (\n). This will consider every character, including space. Here is example:

    int main()
    {
      char string[100], c;
      int i;
      printf("Enter the string: ");
      scanf("%s", string);
      i = strlen(string);      // length of user input till first space
      do
      {
        scanf("%c", &c);
        string[i++] = c;       // reading characters after first space (including it)
      } while (c != '\n');     // until user hits Enter
      string[i - 1] = 0;       // string terminating
    return 0;
    }
    

    How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for loop that takes char by char from input stream (till \n) and apends them to end of string variable, thus forming a complete string same as user input from keyboard.

    Hope this will help someone!

提交回复
热议问题