[英]Why does fgets function in the program below (see detail) interprets the length of string by one extra character?
[英]program does not read string with the defined length in fgets()
我在使用fgets
函數時發現如下:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[10];
fgets(str, 5, stdin);
printf("%s", str);
system("PAUSE");
return 0;
}
如果輸入123456789
,它將輸出1234
。 那是4個字符-而不是我在函數中定義的5個字符。 第五個角色發生了什么?
編輯:標題已更新
這是因為由於C字符串是NUL終止的,所以fgets
考慮了字符串終止符( \\0
),因此,如果傳遞5個字符的緩沖區,則是安全的。
在您的代碼中,您應該執行以下操作:
fgets(str, sizeof(str), stdin);
因為str
是具有已知大小的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.