fgets 没有读取正确的用户输入

fgets not reading proper user input

在给定的代码中 - 在为 扫盲 fgets 键入值时工作正常但是当我们使用 printf 给定输出时它没有给出预期的输出(空白 space 输出).

谁能帮我解决这个问题?

顺便说一句,我正在使用 Visual Studio 2015 来调试我的代码。

#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[MAX] = { 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;
    char line[MAX] = { 0 };
    //int no_of_records = 0;

    //FUNCTION CALL-OUT
    header();

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

    printf("\n\n");

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

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

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

        printf("Population : ");
        fgets(line, sizeof(line), stdin);
        sscanf_s(line, "%d", &cen[i].p);
        printf("\n");

        printf("Literacy : ");
        fgets(line, sizeof(line), stdin);
        sscanf_s(line, "%d", &cen[i].l);
        printf("Literacy : %f", cen[i].l);
        printf("\n");

        printf("_____________________________________");
        printf("\n\n");
    }

    printf("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
    printf("Census Information");
    printf(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
    printf("\n\n");

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

        printf("City Name : %s", cen[i].city);
        printf("\n");

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

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

        printf("_____________________________________");
        printf("\n\n");
    }

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

你的 scanf 有一个 %d 而它应该是 %f。尝试像这样更改您的代码:

    printf("Literacy : ");
    fgets(line, sizeof(line), stdin);
    sscanf(line, "%f", &cen[i].l);  /*  <---- This line ---- */
    printf("Literacy : %f", cen[i].l);
    printf("\n");

%d 查找整数,但您将 l 定义为浮点数,因此 %f 是正确的格式。