Reading from a file and storing the data into a structure

Pages: 12
So what I'm trying to do is to add information to each individual member of the structure with the correct set of data. The output that I'm getting is nothing, yet the my compiler is giving me no errors so It mostly like has to do with the way I structured my code. In my for loop, I only outputted the eventID member because nothing was being display on the command prompt. Any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>

using namespace std;

// Structure.
struct Weather_Event
{
  int eventID; // is the unique int id associated with the weather event.
  std::string CZ_NAME; // is the location associated with the weather event.
  char beginDate[11]; // is the date the event started.
  char beginTime[5]; // is the time the event started.
  std::string eventType; // is the type of weather event.
  int deaths; // are the number of people killed by the weather.
  int injuries; // are the number of people injured by the event.
  int propertyDamage; /* is the $ worth of property damage caused
                         by the event. */
  float beginLatitude; // is the starting latitude for the event.
  float beginLongitude; // is the starting longitude for the event.
};

int main()
{
    // Create an empty vector that will contain the structure.
    vector<Weather_Event>weatherInformation(0);

    Weather_Event data; /* Create an object to access each member in
                           the structure. */

    ifstream weather; // Declare an object to open the file.
    weather.open("weatherdata.csv"); // Open the file.

    if(!weather) // Check to see if the file opens.
        {
          cerr << "Error, opening file. ";
          exit(EXIT_FAILURE); // terminate the program early.
        }

    /* While you're not at the end of the file, keep reading each new
       piece of data. */

    while(weather >> data.eventID >> data.CZ_NAME >> data.beginDate
       >> data.beginTime >> data.eventType >> data.deaths
       >> data.injuries >> data.propertyDamage >> data.beginLatitude
       >> data.beginLongitude)
    {
       /* Add all the data that was added to each member of the
        structure, into the vector. */
       weatherInformation.push_back(data);
    }

    weather.close();

    // Next display the result
    for(size_t i=0; i<weatherInformation.size(); i++)
    {
       cout << "EventID: " << weatherInformation[i].eventID << endl;
    }

    cout << weatherInformation.size();

    return 0;
}
Last edited on
I dont see anything wrong with your code
Interesting, now I'm getting an error called terminated after throwing an instance std:bad alloc. I'm assuming it means bad allocation of memory. It also says that the application has terminated in an unusual way with what() next to std:bad alloc.
Last edited on
Does it not tell where the error is? And what environment are you on?
closed account (SECMoG1T)
How is your data arranged in your file
I recommend you use std::string instead of the C-strings in your structure. Next the problem is likely being caused by a failure of the file reading. You really shouldn't use eof() to control the loop, use the actual read operation.

1
2
3
4
5
6
7
8
9
    while(weather >> data.eventID >> data.CZ_NAME >> data.beginDate
                            >> data.beginTime >> data.eventType >> data.deaths
                            >> data.injuries >> data.propertyDamage >> data.beginLatitude
                            >> data.beginLongitude)
    {
       /* Add all the data that was added to each member of the
        structure, into the vector. */
       weatherInformation.push_back(data);
    }


Then if the read fails for any of the variables you won't be "saving" bad data.
Sorry for the late responses.

ShadowCODE-In response to your first question, no It doesn't tell me where the error is located. In fact, it only tells me what type of error it is, and then it tells me to contact application support team for more information(This error occurs after 30 seconds or more). In response to your second question, I'm using the IDE CodeBlocks.

Andy1992-Since the file is an excel file(.csv) and I'm assuming that you've worked with excel before, each member in the data structure represents the name of column in the data file with values and labels underneath it(each of those values and labels correspond to the name of the column above it).
Jlb, I'm just curious, why do you recommend that I use c-strings as oppose to std:: string?
Also, is eof() usually frowned upon just like system pause because of instability or what?
Last edited on
All right Jlb I've modified my code exactly the way that you did but the problem is that the content in eventID(or any of the members in the structure) isn't getting displayed(remember that I only want to display information that is related to eventID). I checked the size of the vector and it was 0. To me, this mean that nothing is getting added to my vector.
Last edited on
Jlb, I'm just curious, why do you recommend that I use c-strings as oppose to std:: string?

I recommended that you use std::string instead of C-strings.
I recommend you use std::string instead of the C-strings in your structure.


I checked the size of the vector and it was 0. To me, this mean that nothing is getting added to my vector.

Yes if the size is zero then the vector is empty. Which means that there is something wrong with the way you're reading the file. So post your current code, along with a sample of your input file.

Also, is eof() usually frowned upon just like system pause because of instability or what?

The problem with eof() is that you need to check after you try to read the file because eof() will not be set until after you go past the end of the file. And since you don't check the stream state immediately after the read you will use bad data.

I think it possibly has something to do with either line 28 or 52 since those are the only lines of code that mentioned a vector. I either made mistake when creating my vector or that I'm adding the pushback function to the wrong thing. Oh, and I've updated my code. Check my main post.
I'm guessing at line 52 the vector is not really adding the correct data for each member individually, but I'm only adding to the structure itself. Could that be the problem or am I really off?
After you read the data from the file, why don't you try printing each element of the structure. You can also add a test to see if the read failed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    while(weather >> data.eventID >> data.CZ_NAME >> data.beginDate
                            >> data.beginTime >> data.eventType >> data.deaths
                            >> data.injuries >> data.propertyDamage >> data.beginLatitude
                            >> data.beginLongitude)
    {
        
        // Print the structure elements here.
    
        if(!weather) // for debugging purposes.
        {
             cerr << "Read failed";
             return(1);
        }
       weatherInformation.push_back(data);
    }
I tried to the print out each structure elements like this cout << data.eventID etc exactly where you said I should print it but it returns nothing(more like zero if you place it outside of the loop). To me, it means that while statement is not working properly which also means that nothing is getting added to the vector. So I'm guessing that is the culprit.



edit1- actually it's zero for eventID, blank for CZ_NAME and some random number for death(426528 which is totally wrong). Should I initialize all of my members?
Last edited on
To me, it means that while statement is not working properly which also means that nothing is getting added to the vector. So I'm guessing that is the culprit.

The while statement it's self is not the problem, the problem is probably that your not reading the file correctly. But since you don't seem to want to post a sample of your input file I can't really tell what exactly is the problem. Also just saying something isn't working without posting the actual code where you tried doesn't help either. How do I know that you are trying to print the data correctly?

can you briefly explain what you mean by input file?
Is it how the data in the file(weatherdata.csv) that I"m working with is arranged?
how the data is displayed on the screen? sorry I'm just trying to understand the terminology.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
while(weather >> data.eventID >> data.CZ_NAME >> data.beginDate
       >> data.beginTime >> data.eventType >> data.deaths
       >> data.injuries >> data.propertyDamage >> data.beginLatitude
       >> data.beginLongitude)
    {
        // this is how I'm outputting my structure elements(a few examples)
        cout << data.eventID; // this outputs zero
        cout << data.CZ_NAME; // this outputs blank
        cout << data.deaths; // this outputs a random number.
        
        if(!weather) // for debugging purposes.
        {
             cerr << "Read failed";
             return(1);
        }
        
       /* Add all the data that was added to each member of the
        structure, into the vector. */
       weatherInformation.push_back(data);
    }
Last edited on
You have a file named weatherdata.csv, what exactly does this input file contain? Show a sample, at least several lines.

Okay, temporarily change your while statement to :

1
2
3
4
5
6
string line;
while(getline(weather, line))
{
    cout << line << endl;
}


Then show me exactly what the program prints.
Last edited on
Ok, here is a sample of that file and what the program prints(well not as neat as this).

Sample

The labels, like Event_ID, represents the name of the member in my structure(a total of 10).

1
2
3
4
EVENT_ID  	CZ_NAME_STR	BEGIN_DATE	BEGIN_TIME
9991511	        MIAMI-DADE CO.	10/18/1955	800
9991516	        MIAMI-DADE CO.	4/10/1956	1730
9991517	        MIAMI-DADE CO.	4/10/1956	1730
Last edited on
Ok, here is a sample of that file and what the program prints(well not as neat as this).

I need to see exactly what the last snippet I provided produced. Don't pretty it up, cut and past the output exactly as it appears.

The problem is that first line, you need to read it into a string then discard it. But until I see the actual file contents I can't tell you how to proceed.
Ok then this is what appears in the command prompt when I use your edit.
note-This information is from the end of the command prompt.


409650,METROPOLITAN MIAMI-DADE (ZONE),8/26/2012,0,Tropical Storm,0,0,0, ,
409651,INLAND MIAMI-DADE (ZONE),8/26/2012,0,Tropical Storm,0,0,0, ,
413194,MIAMI-DADE CO.,9/19/2012,1815,Thunderstorm Wind,0,0,0,25.69,-80.4
415904,COASTAL MIAMI-DADE COUNTY (ZONE),10/25/2012,500,Tropical Storm,0,0
446320,MIAMI-DADE CO.,4/15/2013,1459,Thunderstorm Wind,0,0,0,25.56,-80.45
461684,MIAMI-DADE CO.,6/29/2013,1317,Thunderstorm Wind,0,0,0,25.9,-80.27
471011,MIAMI-DADE CO.,9/15/2013,1040,Thunderstorm Wind,0,0,0, ,
471014,MIAMI-DADE CO.,9/15/2013,1055,Thunderstorm Wind,0,0,0, ,
495130,MIAMI-DADE CO.,2/12/2014,1639,Thunderstorm Wind,0,0,0,25.91,-80.28
495129,MIAMI-DADE CO.,2/12/2014,1640,Thunderstorm Wind,0,0,0,25.9,-80.27
502087,MIAMI-DADE CO.,4/19/2014,517,Thunderstorm Wind,0,0,0,25.73,-80.23
524178,MIAMI-DADE CO.,6/13/2014,1508,Thunderstorm Wind,0,0,0,25.72,-80.43
524179,MIAMI-DADE CO.,6/13/2014,1510,Thunderstorm Wind,0,0,0,25.71,-80.43
524198,MIAMI-DADE CO.,6/20/2014,1407,Thunderstorm Wind,0,0,0,25.73,-80.23
,,,,,2,13,,,
Pages: 12