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

发布于 2024-12-26 07:50:23 字数 305 浏览 4 评论 0原文

大家好!

这里:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

岛徒 2025-01-02 07:50:23

这是 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.

追星践月 2025-01-02 07:50:23

因为这就是 scanf 的作用。如果您想读取字符串直到换行,请使用 gets EDIT: 或其缓冲区溢出安全表兄弟 fgets (谢谢,@JayC)

Because that's what scanf does. If you want to read a string till newline, use gets EDIT: or its buffer-overflow-safe cousin fgets (thanks, @JayC)

坚持沉默 2025-01-02 07:50:23

scanf 手册页:

Matches a sequence of non-white-space characters

这回答了您的问题。

如果您还需要匹配空格,那么您可能需要在循环中处理它,或者只是使用更传统的方法读取它。

From the scanf man page:

Matches a sequence of non-white-space characters

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.

日记撕了你也走了 2025-01-02 07:50:23

如果您想获取带有空格的输入字符串,您还可以使用 fgets() 函数,如下所示:

char str[50];
printf("Enter a string: ");
fgets(str,50,stdin);

printf("%s",str);  //print the accepted string

If you want to take input strings with spaces you can also use fgets() function as shown below:

char str[50];
printf("Enter a string: ");
fgets(str,50,stdin);

printf("%s",str);  //print the accepted string
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文