Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

input

scanf

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);
like image 412
Wai Hung Tong Avatar asked Dec 05 '12 15:12

Wai Hung Tong


People also ask

How do I scanf a string with spaces?

So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

Can we use scanf () to read string with blank spaces?

Using blank spaces is necessary to get scanf to read only visible characters. It is also an example of how we can use text other than format specifiers in the format string.

Does scanf stop at space?

scanf() just stops once it encounters a whitespace as it considers this variable "done".


2 Answers

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
like image 61
Mike Avatar answered Sep 30 '22 14:09

Mike


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.

like image 21
P.P Avatar answered Sep 30 '22 15:09

P.P