为什么输入在空格字符后断开

Mic*_*nov 2 c string space

大家好!

这里:

#include <stdio.h>

char* getStr( char *c ){
    scanf( "%s" , c );
    return c;
}

int main(){
    char str[ 100 ];
    getStr( str );
    printf( "%s" , str );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你能解释为什么字符串只打印到第一个"空格".即

输入:asd asd

输出:asd

Jef*_*ter 14

这是合同scanf(见http://pubs.opengroup.org/onlinepubs/007904975/functions/scanf.html).它会一直读到下一个空格.

您可以将格式字符串更改为以两个字符串读取,"%s %s"其中将读取由空格分隔的两个字符串.


Ama*_*dan 7

因为那是什么scanf.如果你想读取字符串直到换行,请使用gets EDIT:或其缓冲区溢出安全表兄fgets(谢谢,@ JayC)

  • 或者它的缓冲区溢出安全表兄'fgets' (4认同)