Thread: Reading data from a file

  1. #1
    Registered User
    Join Date
    Nov 2022
    Posts
    5

    Reading data from a file

    Hi!

    I'm trying to read some data from a file. Particularly, this file contains different statistics of different countries, as it follows:

    "Country","Area","Density","HDI"
    "France","643801.27","121.5","0.903"
    "Italy","301230.45","201.3","0.895"
    "Germany","357022.1","232.9","0.943"

    Note: all statistics correspond to float data. Moreover, it contains more rows and columns.

    Now I'm attempting to store each country statistics in an array. Therefore, after having opened the file, this is my code.

    Code:
    float France[3];
    float Germany[3];
    float Italy[3];
    float store[9];
    
    int i=0;
    
    while(i<10){
      fscanf(file,"\"%f\"",store[i];
      i++;
    }
    
    for(i=0;i<3;i++){
      France[i]=store[i];
      Italy[i]=store[i+3];
      Germany[i]=store[i+6];
    }
    However, when I print the arrays France, Italy and Germany it prints 0.000000, so I think fscanf is not being well used. Why? What should I do?

    Thank you very much.

  2. #2
    Registered User
    Join Date
    Sep 2022
    Posts
    55
    Note: all statistics correspond to float data.
    No. There is a head line. And every further line begins with a field containing the country name. How is this ever float data?


    Moreover, it contains more rows and columns.
    Then you have to consider this in your program code.


    so I think fscanf is not being well used
    The compiler should have at least warned you about passing the float instead of passing the address of the float that receives the value.




    Consider to read the data line by line.
    Ignore lines that don't contain data.
    Tokenize the lines.
    Ignore tokens that don't contain data.
    Convert tokens that contain data.

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Country isn't a float, it's a string and you should read it as a string.
    Also you should skip the first line.
    Do you have to use different arrays ? It would be easier to use an array of structs.
    Code:
        struct Data
        {
            char  country[32];
            float area,
                  density,
                  hdi;
        };
    
        struct Data countries[10];

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading data from file
    By kermos in forum C Programming
    Replies: 16
    Last Post: 09-02-2011, 07:54 AM
  2. Replies: 13
    Last Post: 05-31-2009, 11:30 AM
  3. Reading from a file and using the data
    By Ste_Mulv in forum C Programming
    Replies: 3
    Last Post: 04-01-2009, 07:44 AM
  4. help with reading data file
    By loso44x in forum C Programming
    Replies: 13
    Last Post: 10-02-2005, 06:12 PM
  5. Replies: 2
    Last Post: 06-16-2005, 10:03 AM

Tags for this Thread