strlen()和fgets()搭配使用時的注意要點

沒有用到fgets()時:

char *a="123456789";
printf("%d\n",strlen(a));

那麼輸出9,但不包括結束字符(即 null 字符)

用到fgets時

char a[100];
fgets(a,100,stdin);
printf("%ld",strlen(a));

當輸入:123456789

那麼輸出10,原因在於fgets函數,查看fgets系統手冊時(在terminal運行man fgets),會看到如下:

fgets()  reads in at most one less than size characters from stream and
       stores them into the buffer pointed to by s.  Reading  stops  after  an
       EOF  or a newline.  If a newline is read, it is stored into the buffer.
       A terminating null byte ('\0') is stored after the  last  character  in
       the buffer.

翻譯過來:

fgets()最多從流中讀取小於大小的字符,並將它們存儲到s所指向的緩衝區中。在EOF或換行符之後停止讀取。如果讀取換行符,則將其存儲到緩衝區中。終止的空字節(\ 0)存儲在緩衝區中的最後一個字符之後。

意味着fgets()函數將讀入‘\n’後,會存儲進去字符串裏面,然後再放'\0',所以輸出是10.我們可以用下面的代碼來測試一下是否如此呢。

#include<stdio.h>
#include<string.h>
int main(){
        char a[100];
        fgets(a,100,stdin);

        printf("%ld\n",strlen(a));
        for(int i=0;i<strlen(a);i++)
        {
                if(a[i]=='\n')
                        printf("\\n");
                else if(a[i]=='\0')
                        printf("end");
                else
                        printf("%c",a[i]);
        }
        printf("\n");
        return 0;

}

輸入:123456789  結果如下:

由此可以看出,‘\n’會在strlen()函數之中統計出來的。

那使用scanf()函數呢

使用scanf()函數並不會把‘\n’放進去字符串裏面去。那麼上面輸出長度自然是9

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章