在scanf之后使用fgets [英] Using fgets after scanf
问题描述
我想摆脱缓冲区溢出,我使用了 fgets
而不是 scanf
来限制字符.但是,每当我在 fgets
之前用 scanf
输入内容时,它就无法正常工作.
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.
此代码正常工作
#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?
推荐答案
请勿在同一代码中将 scanf()
与 fgets()
混合使用.
Don't mix scanf()
with fgets()
in the same code.
scanf(%d",& choice);
不会消耗掉所有的 line -它留下了结尾的'\ n'
,以便以后的 fgets()
用作空行.
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()
很难以安全的方式使用.
scanf()
is difficult to use in a secure fashion.
这篇关于在scanf之后使用fgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!