7

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);
2
  • %s isn't what you want if you want to add spaces, you want to use the negated scanset Commented Dec 5, 2012 at 17:01
  • 2
    Note: scanf("%[^\n]", comment will not scan anything into comment if the first char is '\n', leaving comment uninitialized. Commented Oct 12, 2015 at 18:21

4 Answers 4

22

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
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe "%99[^\n]" in this case? BTW: This does have the side effect that the \n is not consumed and still in the input buffer. Maybe use " %99[^\n]" (leading space) if this was in a loop?
13

scanf() with %s as format specifier reads a sequence of characters starting from the first non-whitespace character until (1) another whitespace character or (2) upto the field width if specified (e.g. scanf("%127s",str); -- read 127 characters and appends null byte as 128th), whichever comes first. And then automatically append null byte at the end. The pointer passed my be large enough to hold the input sequence of characters.

You can use fgets to read the whole line:

fgets(comment, sizeof comment, stdin);

Note that fgets reads the newline character as well. You may want to get rid of the newline character from the comment.

Comments

3

instead of scanf use fgets on stdin in order to read the whole line.

Comments

1

You can make use of gets(), getline() functions to read string from stdin.

1 Comment

gets() has been deprecated since C99 and removed since C11. Why is the gets function so dangerous that it should not be used?. And getline() is a POSIX function. It doesn't exist in C

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.