【发布时间】:2020-11-24 12:45:00
【问题描述】:
我想摆脱缓冲区溢出,我使用fgets 而不是scanf 来限制字符。但是每当我在fgets 之前输入scanf 时,它就无法正常工作了。
此代码工作正常
#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);
}
此代码未正确读取名称
#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 */
}
为什么会发生,我该如何解决?
【问题讨论】:
-
在调用
fgets()之前使用\n -
这能回答你的问题吗:scanf leaves new line char in the buffer