fgets 不等待用户输入

fgets not waiting for user input

在给定的代码中,fgets 没有等待输入。

我尝试使用 scanf,但出现异常错误(在 0x0F74DDF4 (ucrtbased.dll) 处抛出异常)。我正在使用 Visual Studio 2015 来调试我的代码。谁能解释为什么 fgets 不等待输入?

#include<stdio.h>
#include<stdlib.h>
#include<process.h>

//GLOBAL-VARIABLE DECLARTION
#define MAX 1000

//GLOBAL-STRUCTURES DECLARATION
struct census
{
char city[MAX];
long int p;
float l;
};

//GLOBAL-STRUCTURE-VARIABLE DECLARATION
struct census cen[] = { 0,0,0 };

//USER-DEFINED FUNCTION
void header();

void header()
{
printf("*-*-*-*-*CENSUS_INFO*-*-*-*-*");
printf("\n\n");
}

//PROGRAM STARTS HERE
main()
{   
//VARIABLE-DECLARATION
int i = 0, j = 0;
//int no_of_records = 0;

//FUNCTION CALL-OUT
header();

printf("Enter No. of City : ");
scanf_s("%d", &j);

printf("\n\n");

printf("Enter Name of City, Population and Literacy level");
printf("\n\n");

for (i = 0;i < j;i++)
{
    printf("City No. %d - Info :", i + 1);
    printf("\n\n");

    printf("City Name :");
    fgets(cen[i].city, MAX, stdin);
    printf("\n");

    printf("Population : ");
    scanf_s("%d", &cen[i].p);
    printf("\n");

    printf("Literacy : ");
    scanf_s("%f", &cen[i].l);
    printf("\n");
}

//TERMINAL-PAUSE
system("pause");
}

我总是使用 fgets 然后是 sscanf

在顶部声明,

char line[MAX];

然后用fgets得到一行,sscanf从中解析出int值,

printf("Enter No. of City : ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &j);

l

的相似模式
printf("Literacy : ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &cen[i].l);

当您输入城市数并按 Enter 时,scanf 不会从输入中读取换行符。 fgets 然后尝试读取但发现换行符,并立即停止。

不要用scanf读入数字,先用fgets读入字符串再用sscanf(或strtol/strtof/strtod)转成数字。

char temp[LIMIT];
if(fgets(temp, LIMIT, stdin)) {
    if(sscanf(temp, "%d", &j) == 1) {
        // Ok
    }
    else {
        // Handle sscanf error
    }
}
else {
    // Handle fgets error
}