C 扫描后使用FGET
我想消除缓冲区溢出,我使用C 扫描后使用FGET,c,function,scanf,fgets,C,Function,Scanf,Fgets,我想消除缓冲区溢出,我使用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); retur
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 */
}
#包括
int main()
{
字符名[10];
printf(“你是谁?\n”);
fgets(名称,10,标准名称);
printf(“很高兴认识你,%s.\n”,姓名);
返回(0);
}
此代码无法正确读取名称
#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 */
}
#包括
#包括
#定义最大值15
int new_acc();
int view_list();
int main(){
int一=1,二=2,三=3,四=4,五=5,六=6,七=7,选择;
int新账户,列表;
printf(“%d.创建新帐户\n”,一个);
printf(“输入您的选择:”);
scanf(“%d”,选择(&C);
如果(选项==1){new_account=new_acc();}
返回0;
}
int new_acc(){
字符名称[最大值]、地址、帐户;
printf(“输入您的姓名:”);
fgets(name,MAX,stdin);/*这是代码*/
}
为什么会发生这种情况?我如何修复它?不要将scanf()
与fgets()
混合在同一代码中
scanf(“%d”和&choice)
不会消耗所有的行-它会将尾部的'\n'
留给后面的fgets()
作为空行使用
scanf()
很难以安全的方式使用。在调用fgets()之前使用\n
这是否回答了您的问题:那么如何编写fgets而不是scanf?字符缓冲区[80];fgets(缓冲区、缓冲区大小、标准输入);选择=atoi(缓冲区)代码>是一个简单的选择。它省略了各种错误检查,但有一些东西可以让你继续。我不明白。