2016-11-13 53 views
0

我發現讀字符串:程序不與在與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個字符。第五個角色發生了什麼?

編輯:標題更新

+2

第五個字符爲空字符。字符串以C語言中的空終止符結束 – saygins

+0

@saygins抱歉放棄編輯,但我同時在作品中同時進行了大量編輯。和NULL(空指針的預處理器宏)與NUL(空字符)不同:http://stackoverflow.com/questions/2911089/null-terminating-a-string –

+1

請參閱[fgets](http: (_en.cppreference.com/w/c/io/fgets)(_從給定的文件stream_中最多讀取** count - 1 **個字符) – BLUEPIXY

回答

0

這是因爲由於C-字符串是NUL終止,fgets需要一個字符串結束(\0)考慮進去,所以如果你通過一個5字符緩衝區,它是安全的。

在你的代碼,你應該做的:

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

因爲str是已知大小的數組。