驗證fgets末尾自動添加的字符是'\0' 還是 '\n\'?


最近寫代碼經常使用字符串,對於輸入函數fgets網上有人說輸入結束會在末尾自動添加’\n’,還有人說添加的是’\n’,我決定親自驗證:

#include "iostream"
#include "stdio.h"
#include "stdio_ext.h"
#include "stdlib.h"
#include "string.h"
using namespace std;
int main(int argc, char const *argv[])
{
    char buf[1024];
    while(true){
        __fpurge(stdin);
        int len = 0;

        fgets(buf,sizeof(buf),stdin);

        cout<<"buf="<<buf;
        len = strlen(buf);
        cout<<"valid size="<<len<<endl;
        cout<<"actual size="<<sizeof(buf)<<endl;

        if (buf[len] == '\0')
        {
            cout<<"is 0"<<endl;
        }else if (buf[len] == '\n')
        {
            cout<<"is n"<<endl;
        }

    }
    return 0;
}
PC測試結果:
iuc@iuc-linux ~/Project/LinuxTestCode $ ./fgets 
qqqq
buf=qqqq
valid size=5
actual size=1024
is 0

分析結果:
fgets輸入函數在末尾自動添加的'\0'而不是'\n'.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM