2016-01-30 29 views
2

在給定的代碼中 - 輸入值爲識字fgets工作正常,但是當我們使用printf給定輸出時,它不會給出預期輸出(空白輸出)。fgets沒有讀取正確的用戶輸入

任何人都可以幫助我解決這個問題嗎?

順便說一句我正在使用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"); 
} 

回答

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尋找一個整數,但你必須定義爲float l,所以%f是正確的格式。

+0

這確實是一個問題,但它不能解釋*空格輸出*。 – chqrlie

+0

@chqrlie現在感謝很多人的工作:) – Eddy

+0

@Eddy:伯爵是一個感謝。 – chqrlie