最近寫代碼經常使用字符串,對於輸入函數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'.