简体   繁体   中英

Why does my program only read the last line from a file? (C++)

So I am required to make this file reading program that outputs information in the form of test marks in a table, then finds their average, and finally finds both highest and lowest value for a test. This program is required to make use of structures and arrays. I have tried building it with a function to read marks from the file. However for some reason, while the names were read and displayed perfectly, the program would only read test marks from the final line in the file. I initially suspected that there is a problem in the looping, however to my limited knowledge I coded it correctly, and I tried messing with the structure arrays next, to no avail. Where did I went wrong?

//variables
const int ROWS = 6;
const int COLS = 3;
    
//structure
struct marks
    {
    string name;
    float test, total;
    float average, MAX, MIN;
    };
//functions
void input(marks []);

void input(marks s[])
{
    int i,j;
    fin.open("EE209_marks.txt");
    for (i=0; i<ROWS;i++)
    {
        fin>> s[i].name;
        for (j=0; j<COLS; j++)
        {
            fin>> s[i].test;
        }
    }
}

int main()
{
int i,j;
 marks studs[6];
    input (studs);

cout<< left;
for (i=0; i<ROWS;i++)
    {
        cout<<setw(18)<< studs[i].name;
    for (j=0; j<COLS; j++)
    {cout <<setw(8)<< studs[j].test;}
    cout<<endl;
    }

Right now, you only have room for one test per student ( float test ), but it seems that you really have 3 tests per student. Therefore, you should do something like replace float test with float tests[COLS] , and then in your input function, populate it with fin >> s[i].tests[j] .

Also, you're printing it out incorrectly - you use the variable j in your main function to represent the column number (j=0; j<COLS) , but then you access studs[j] . After you fix your input function, you should see your printing logic should be almost identical to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM