Mroog
Mroog

Reputation: 7

C++: How to read from specific line in .dat file

I am new to C++, I am trying to construct an array of pointers to type Students by reading through a .dat file where each line is of this form:

101 Jones 92.7 54.3 88 .4*88+.3*(92.7+54.3)

Each line will be an instance of struct and stored into an array of pointers to Students. Here is my code:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
const int N = 100;
struct Students{
        int classid;
        string lastname;
        float exam1;
        float exam2;
        float final;
        float score;
};


int main(void){
        Students* s[N];
        ifstream input;
        ofstream output; 
        input.open("examscores.dat");
        for(int i=0; i< 10; i++){
                s[i] = new Students; 
                input >> s[i]->classid >> s[i]->lastname >> s[i]->exam1 >> s[i]->exam2 >> s[i]->final >> s[i]->score;
        }
        cout << s[0]->classid << endl;
        cout << s[4]->classid << endl;
        cout << s[5]->classid << endl;
return 0;
}   

I expect this output:

101
105
106

but I get:

101
0
0

Upvotes: 0

Views: 3648

Answers (1)

Simon
Simon

Reputation: 32873

.4*88+.3*(92.7+54.3) does not fit in a float. You must read it as a string a parse the expression yourself.

When you use input >> ... >> s[i]->score it reads the .4 but leaves the rest (*88+.3*(92.7+54.3)) in the buffer and screws up subsequent reads.

Quickfix: replace float score; by std::string score;

Upvotes: 3

Related Questions