Difference between fgets and gets

后端 未结 4 1994
面向向阳花
面向向阳花 2021-01-21 03:59

What is the difference between fgets() and gets()?

I am trying break my loop when the user hits just \"enter\". It\'s working well with

4条回答
  •  甜味超标
    2021-01-21 04:48

    A difference between gets() and fgets() is that fgets() leaves the newline in the buffer. So instead of checking whether the first element of the input is 0, check whether it's '\n';

    fgets(cat[i].name, sizeof cat[i].name, stdin);
    if (cat[i].name[0] == '\n' || cat[i].name[0] == 0) {
        // empty line or no input at all
        break;
    } else {
        // remove the trailing newline
        int len = strlen(cat[i].name);
        cat[i].name[len-1] = 0;
    }
    

提交回复
热议问题