In the given code - while typing value for Literacy fgets
works fine but when we use printf to given output it do not give expected output (blank space output).
Can anyone help me in this issue?
BTW I'm using Visual Studio 2015 for debugging my code.
#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");
}
Your scanf has a %d
where it should be a %f
. Try changing your code like this:
printf("Literacy : ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &cen[i].l); /* <---- This line ---- */
printf("Literacy : %f", cen[i].l);
printf("\n");
The %d
looks for an integer, but you have l
defined as a float, so %f
is the proper format.