C语言 如何使用 scanf() 扫描包含空格的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13726499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I scan strings with spaces in them using scanf()?
提问by Wai Hung Tong
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.
我想编写一个子程序,用户可以在其中输入他们的评论。我使用scanf("%s", X)并让他们输入注释,但它只能存储字符串中空格键之前的单词。
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);
回答by Mike
Rather than the answers that tell you notto use scanf(), you can just the the Negated scansetoption of scanf():
而不是告诉您不要使用的答案scanf(),您可以只使用 的否定扫描集选项scanf():
scanf("%99[^\n]",comment); // This will read into the string: comment
// everything from the next 99 characters up until
// it gets a newline
回答by P.P
scanf()with %sas 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.
带有%s格式说明符的scanf()读取从第一个非空白字符开始的字符序列,直到 (1) 另一个空白字符或 (2) 指定的字段宽度(例如scanf("%127s",str);- 读取 127 个字符并附加空字节作为第 128 个) ), 以先到者为准。然后在末尾自动附加空字节。传递的指针足够大以容纳输入的字符序列。
You can use fgetsto read the whole line:
您可以使用fgets读取整行:
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.
请注意, fgets 也会读取换行符。您可能希望从comment.
回答by eyalm
instead of scanf use fgetson stdin in order to read the whole line.
而不是fgets在 stdin 上使用 scanf来读取整行。
回答by Viswesn
You can make use of gets(), getline()functions to read string from stdin.
您可以使用gets(),getline()函数从 中读取字符串stdin。

