简体   繁体   English

为什么我的程序只读取文件的最后一行? (C++)

[英]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.该程序需要使用结构和 arrays。 I have tried building it with a function to read marks from the file.我尝试使用 function 构建它以从文件中读取标记。 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.我最初怀疑循环中存在问题,但是据我所知,我正确地编码了它,然后我尝试弄乱 arrays 结构,但无济于事。 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.现在,每个学生只能进行一次测试( float test ),但似乎每个学生确实有 3 次测试。 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] .因此,您应该执行类似将float test替换为float tests[COLS]的操作,然后在input function 中使用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] .此外,您打印不正确 - 您在main function 中使用变量j来表示列号(j=0; j<COLS) ,但随后您访问studs[j] After you fix your input function, you should see your printing logic should be almost identical to it.修复input function 后,您应该看到您的打印逻辑应该几乎相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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