简体   繁体   English

程序无法在fgets()中读取具有定义长度的字符串

[英]program does not read string with the defined length in fgets()

I found when I use the fgets function like so: 我在使用fgets函数时发现如下:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[10];
    fgets(str, 5, stdin);

    printf("%s", str);
    system("PAUSE");

    return 0;
}

If I input a 123456789 , it will output a 1234 . 如果输入123456789 ,它将输出1234 That's 4 characters - not the 5 I have defined in the function. 那是4个字符-而不是我在函数中定义的5个字符。 What is happening to the fifth character? 第五个角色发生了什么?

edit: title updated 编辑:标题已更新

that's because since C-strings are NUL terminated, fgets takes the string terminator ( \\0 ) into account, so if you pass a 5-char buffer, it is safe. 这是因为由于C字符串是NUL终止的,所以fgets考虑了字符串终止符( \\0 ),因此,如果传递5个字符的缓冲区,则是安全的。

In your code, you should do: 在您的代码中,您应该执行以下操作:

fgets(str, sizeof(str), stdin);

since str is an array with known size. 因为str是具有已知大小的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM