0

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
4

1 回答 1

3

.4*88+.3*(92.7+54.3)不适合float. 您必须将其作为字符串读取,然后自己解析表达式。

当您使用input >> ... >> s[i]->score它时,它会读取.4但将其余的 ( *88+.3*(92.7+54.3)) 留在缓冲区中并搞砸后续读取。

快速修复:替换float score;std::string score;

于 2013-09-22T03:45:07.530 回答