0

In a structs lab assignment that I am doing, the question asks to read statistics about 10 different dinosaurs from a text file and store that information into a struct. I get no errors in the code, however the console is just totally blank.I think i am definitely referencing the array wrong and I have no idea how to fix this.

My code is as follows:

using namespace std;
const int LIST_SIZE = 10;
struct dinosaurInfo {
    string dinosaurName;
    string dinosaurClass;
    string dinosaurHabitat;
    double dinosaurSize;
    double dinosaurWeight;
    int battleRating;
};

void loadData(ifstream& getData, dinosaurInfo *data);

int main()
{
    dinosaurInfo data[LIST_SIZE];
    ifstream getData;
    ofstream giveData;
    getData.open("dinosaurRecords.txt");
    if (!getData)
    {
        cout << "Error loading in data." << endl;
    }

    loadData(getData, data);
    getData.close();

    system("pause");
    return 0;
}

void loadData(ifstream& getData, dinosaurInfo *data)
{
    while (!getData.eof()) 
    {
        for (int i = 0; i < 10; i++)
        {
            getline(getData, data[i].dinosaurName);
            getline(getData, data[i].dinosaurClass);
            getline(getData, data[i].dinosaurHabitat);
            cin.ignore();
            getData >> data[i].dinosaurSize;
            getData >> data[i].dinosaurWeight;
            getData >> data[i].battleRating;
        }
    }

The text file is formatted as follows: (dinosaurname class habitat height weight battle rating). screenshot of the file below

May someone please help me fix this?

  • Please post the contents of your input file in textual form instead of linking to an image of the contents. – R Sahu Mar 12 '19 at 05:51

1 Answers1

0

The root problem is use of getline to read the string elements.

getline(getData, data[i].dinosaurName);
getline(getData, data[i].dinosaurClass);
getline(getData, data[i].dinosaurHabitat);

Since these are tokens separated by space, use the >> operator instead to read them.

getData >> data[i].dinosaurName;
getData >> data[i].dinosaurClass;
getData >> data[i].dinosaurHabitat;

Also, avoid use of

while (!getData.eof()) { ... }

See Why is iostream::eof inside a loop condition considered wrong? for details.

A cleaned up version of you function would be:

void loadData(ifstream& getData, dinosaurInfo *data)
{
    // Stop when 10 records are read.
    // Also, stop reading when getData is an error state.
    for (int i = 0; i < 10 && getData; i++)
    {
        getData >> data[i].dinosaurName;
        getData >> data[i].dinosaurClass;
        getData >> data[i].dinosaurHabitat;
        getData >> data[i].dinosaurSize;
        getData >> data[i].dinosaurWeight;
        getData >> data[i].battleRating;
    }
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247