【问题标题】:Using fgets after scanf [duplicate]在 scanf 之后使用 fgets [重复]
【发布时间】: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 */
}

为什么会发生,我该如何解决?

【问题讨论】:

标签: c function scanf fgets


【解决方案1】:

不要在同一代码中将scanf() 与fgets() 混用。

scanf("%d",&amp;choice); 不会消耗所有 行 - 它会将尾随的 '\n' 留给后面的 fgets() 作为空行使用。

scanf() 很难以安全的方式使用。

【讨论】:

  • 那怎么写fgets而不是scanf呢?
  • char buffer[80]; fgets(buffer, sizeof buffer, stdin); choice = atoi(buffer); 是一个简单的替代方案。它省略了各种错误检查,但可以帮助您前进。
  • 我没有得到。
猜你喜欢
  • 2021-12-17
相关资源
最近更新 更多