Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot get value when working with struct in c

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading