c - fgets 不等待用户输入

标签 c input fgets

在给定的代码中,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");
}

最佳答案

当您输入城市数并按 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
}

关于c - fgets 不等待用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064671/

相关文章:

c++ - 80 年代后期的老 friend : What was the emacs-like editor that came with MS C 5. 0(用于 DOS)?

c - 为什么 fscanf/scanf 正在更改 Ideone.com 上先前扫描的变量的值?

c 程序.数据验证。将字符转换为整数

java - 从/向路径读取和写入 CSV

c - 如何从文本文件存储 STDIN

c - 如何在 C 中打印一个数组覆盖另一个数组?

c - 数组值改写

javascript - 如何生成 ids/数值并将其附加到 jsp 中的输入 id 属性

c - 为什么不是 scanf ("%*[^\n]\n");和 scanf ("%*[^\n]%*c");清除挂起的换行符?

c - fgets和gets之间的区别