在给定的代码中,fgets没有等待输入。
我尝试使用scanf,但它会出现异常错误(Exception thrown at 0x0F74DDF4 (ucrtbased.dll))。我正在使用Visual Studio 2015调试我的代码。有人能解释一下为什么fgets没有等待输入吗?
我尝试使用scanf,但它会出现异常错误(Exception thrown at 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");
}
scanf
替换为scanf_s
;如果你使用了%s
、%c
或%[
格式,这在想要模拟fgets
时很可能会出现,你必须为每个格式在scanf_s
中提供一个最大缓冲区大小。但我同意@jamieguinan的观点:对于交互式输入,始终使用两步方法:首先读取一行,然后从该行读取数据。 - M Oehmscanf_s("%f", &cen[i].l);
不会读取紧随数字后面的'\n'
。接下来的fgets(cen[i].city, MAX, stdin);
会读取这个字符'\n'
。建议不要使用scanf()
。 - chux - Reinstate Monica