[英]Input a character pointer Array using Scanf , but when i input the String after “space” is truncated
[英]Why the input breaks after a space character
大家好!
这里:
#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
这是scanf
的合同(参见http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html )。 它会一直读到下一个空格。
您可以将格式字符串更改为以"%s %s"
两个字符串读取,这将读取由空格分隔的两个字符串。
因为这就是scanf
作用。 如果你想读取一个字符串直到换行,使用gets
编辑:或其缓冲区溢出安全表兄格fgets
(谢谢,@ JayC)
从scanf
手册页:
Matches a sequence of non-white-space characters
这回答了你的问题。
如果您还需要匹配空格,那么您可能需要在循环中处理它,或者只是使用更传统的方法来读取它。
如果要使用带空格的输入字符串,还可以使用fgets()函数,如下所示:
char str[50];
printf("Enter a string: ");
fgets(str,50,stdin);
printf("%s",str); //print the accepted string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.