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

时间:2016-01-30 06:18:21

标签: c fgets

在给定的代码中 - 虽然识字 fgets的输入值工作正常,但是当我们使用printf给出输出时,它不会给出预期的输出(空格输出)。

有谁可以帮我解决这个问题?

BTW我正在使用 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");
}

1 个答案:

答案 0 :(得分:3)

您的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是正确的格式。

相关问题