I am writing a program which prompt user to enter information of cities (in the program I test with 2 cities: city a, b
) then print out these value. Each city has 4 value: name
, income
, population
and literarte_rate
. The problem is when I enter information literrate_rate
, it automatically print out 0.000000
and save it to variable. I am still able to enter value to it and the next infomation.
Input
city name: qwerty 123 !@#
income: 789
population: 123456
literation: 0.000000685
city name: asdfgh 456 $%^
income: 456
population: 999999
literation: 0.00000065684
Output
city name: qwerty 123 !@#
income: 789
population: 123456
literation: 0.00
city name: asdfgh 456 $%^
income: 456
population: 999999
literation: 0.00
This is my code
#include <stdio.h>
#include <string.h>
typedef struct City
{
char name[51];
double income;
unsigned int population;
double literate_rate;
}city;
void input(city *tmp);
void output(city tmp);
int main(){
city a, b;
input(&a);
input(&b);
output(a);
output(b);
return 0;
}
void input(city *tmp){
printf("city name: ");
fgets(tmp->name, 50, stdin);
tmp->name[strlen(tmp->name)-1]='\0';
printf("income: ");
scanf("%lf", &tmp->income);
while(getchar()!='\n');
printf("population: ");
scanf("%d", &tmp->population);
while(getchar()!='\n');
printf("literation: ");
printf("%lf", &tmp->literate_rate);
while(getchar()!='\n');
}
void output(city tmp){
printf("\ncity name: %s", tmp.name);
printf("\nincome: %.2f", tmp.income);
printf("\npopulation: %d", tmp.population);
printf("\nliteration: %.2f", tmp.literate_rate);
}
I have tried to use while(getchar()!='\n');
after each scanf
with number but it does not solve the problem.
So how to fix it and make more efficient?
Thanks in advance.
CodePudding user response:
You have missed the call to scanf:
printf("%lf", &tmp->literate_rate);
should be
scanf("%lf", &tmp->literate_rate);
Also, you should check the result of scanf (which returns the number of scanned tokens) to make sure the scan was successful.