为什么输入在空格字符后中断
大家好!
这里:
#include <stdio.h>
char* getStr( char *c ){
scanf( "%s" , c );
return c;
}
int main(){
char str[ 100 ];
getStr( str );
printf( "%s" , str );
return 0;
}
您能否解释一下为什么只打印字符串直到第一个“空格”。 即
输入:asd asd
输出:asd
Hello guys!
Here:
#include <stdio.h>
char* getStr( char *c ){
scanf( "%s" , c );
return c;
}
int main(){
char str[ 100 ];
getStr( str );
printf( "%s" , str );
return 0;
}
Could you please explain why is the string printed only until the first "space".
i.e.
input: asd asd
output: asd
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是
scanf
的契约(参见 http://pubs .opengroup.org/onlinepubs/007904975/functions/scanf.html)。它会读取直到遇到下一个空格。您可以更改格式字符串以读取两个字符串
"%s %s"
,这将读取由空格分隔的两个字符串。That's the contract of
scanf
(see http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html). It reads until the next whitespace encountered.You could change your format string to read in two strings as
"%s %s"
which will read two strings separated by whitespace.因为这就是
scanf
的作用。如果您想读取字符串直到换行,请使用gets
EDIT: 或其缓冲区溢出安全表兄弟fgets
(谢谢,@JayC)Because that's what
scanf
does. If you want to read a string till newline, usegets
EDIT: or its buffer-overflow-safe cousinfgets
(thanks, @JayC)从
scanf
手册页:这回答了您的问题。
如果您还需要匹配空格,那么您可能需要在循环中处理它,或者只是使用更传统的方法读取它。
From the
scanf
man page:That answers your question.
If you need to match whitespace as well then you may need to process it in a loop, or just read it using more traditional methods.
如果您想获取带有空格的输入字符串,您还可以使用 fgets() 函数,如下所示:
If you want to take input strings with spaces you can also use fgets() function as shown below: