在给定的代码中--在为扫盲输入值时, fgets工作得很好,但是当我们使用printf对给定的输出进行输出时,它不会给出预期的输出(空白输出)。
有人能在这个问题上帮我吗?
顺便说一下,我正在使用Visual 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");
}发布于 2016-01-30 06:31:14
扫描程序有一个%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是正确的格式。
https://stackoverflow.com/questions/35098723
复制相似问题