How can I scan strings with spaces in them using scanf()?

c, input, scanf

Solution

Rather than the answers that tell you not to use `scanf()`, you can just the the Negated scanset option of `scanf()`:

scanf("%99[^\n]",comment); // This will read into the string: comment 
                           // everything from the next 99 characters up until 
                           // it gets a newline

Problem

I want to write a sub-program in which a user can input their comment. I use `scanf("%s", X)` and let them input a comment, but it can only store the word before a space bar in the string. How can I solve this problem in order to store a whole sentence into a string or a file? My code is presented below: ``` FILE *fp; char comment[100]; fp=fopen("comment.txt","a"); printf("You can input your comment to our system or give opinion to the musics :\n"); scanf("%s",comment); fputs(comment,fp); ```

Original source

Related problems