首页 > 技术文章 > 对fgets末尾'\0'的处理

iucforever 2016-03-12 11:06 原文

之所以要对fgets自动添加的字符进行处理的原因之一是:当你想比较输入的字符时,你会发现输入的字符和源码用来进行对比的字符一模一样,但是使用strcmp比较时就是不一样,原因就是fgets对输入字符添加了一个字–符造成的.

怎么造成的呢?

strcmp会比较这个字符串所有的内容,长度都不一样,肯定不同.

如何解决?

把输入字符长度"截去"一个的就行    
#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];
    char buf1[] = "www";
    int len_buf = 0;
    int len_buf1 = 0;
    while(true){
        __fpurge(stdin);

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

        cout<<"buf="<<buf;
        cout<<"buf1="<<buf1<<endl;
        len_buf = strlen(buf);
        buf[len_buf-1] = '\0'; //在这里截去
        len_buf1 = strlen(buf1);
        cout<<"len_buf="<<len_buf<<endl;
        cout<<"len_buf1="<<len_buf1<<endl;

        // if (strncmp(buf,buf1,3) == 0)
        if (strcmp(buf,buf1) == 0)
        {
            cout<<"is equal"<<endl;
        }else {
            cout<<"isn't equal"<<endl;
        }
    }
    return 0;
}

推荐阅读