Using fgets after scanf [duplicate]

*爱你&永不变心* 提交于 2021-01-10 03:29:25

问题


I want to get rid of buffer overflow and I am using fgets instead of scanf to limit the characters. But whenever I enter something with scanf before fgets, it doesn't work correctly anymore.

This code works correctly

#include <stdio.h>
int main()
{
 char name[10];
 printf("Who are you? \n");

 fgets(name,10,stdin);                   

 printf("Good to meet you, %s.\n",name);
 return(0);
}

This code does not read name correctly

#include <stdio.h>
#include <stdlib.h>
#define MAX 15

int new_acc();
int view_list();
int main(){    
    int one=1, two=2, three=3, four=4, five=5, six=6, seven=7, choice;
    int new_account, list;

    printf("%d. Create new account\n",one);

    printf("Enter you choice: ");
    scanf("%d",&choice);

    if (choice==one){new_account = new_acc();}
    return 0;
}

int new_acc(){
    char name[MAX], address, account;

    printf("Enter your name: ");
    fgets(name, MAX, stdin);          /* it is the code */
}

Why is it happening and how do I fix it?


回答1:


Don't mix scanf() with fgets() in the same code.

scanf("%d",&choice); does not consume all the line - it leaves the trailing '\n' for the later fgets() to consume as an empty line.

scanf() is difficult to use in a secure fashion.



来源:https://stackoverflow.com/questions/61642572/using-fgets-after-scanf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!