验证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'.