使用文件和结构读取数据并输出数据

Using files and structs to read data and output it

本文关键字:数据 输出 读取 结构 文件      更新时间:2023-10-16

Mike 85 83 77 91 76 CSC

马克 80 90 95 93 48 CSC

安德森 78 81 11 90 73 巴士

布莱尔 92 83 30 69 87 欧洲经委会

苏茜 23 83 30 69 87 ARC

卡洛斯 46 76 90 54 38 大众通信

所以我有这个文件,我需要读取它的数据并使用结构体通过控制台输出它,我已经设法阅读了迈克的名字和他的分数和教师,但这就是我卡住的地方,我怎么能继续阅读?

这是我的代码

struct student {
    string name;
    int scores[5];
    string faculty;
};

void main() {
    student x;
    ifstream myfile("D:\Test\MIUCS.txt");
    myfile >> x.name;
    for (int j = 0; j < 5; j++) {
            myfile >> x.scores[j];
        }

    myfile >> x.faculty;

    cout << x.name << " ";
    for (int k = 0; k < 5; k++) {
        cout << x.scores[k] << " ";
    }

    cout << x.faculty << endl;

}

提示:我的教授说要使用我无法真正实现的类型学生(结构(数组,任何帮助将不胜感激,谢谢。

如何继续阅读?

将代码包装在while循环中读取/写入。继续阅读和写作,直到没有可读的东西。

while (  myfile >> x.name )
{
   for (int j = 0; j < 5; j++)
   {
      myfile >> x.scores[j];
   }
   myfile >> x.faculty;
   // If there was any error in reading from myfile, break out of the loop.    
   if ( !myfile )
   {
      break;
   }
   cout << x.name << " ";
   for (int k = 0; k < 5; k++)
   {
      cout << x.scores[k] << " ";
   }
   cout << x.faculty << endl;
}

您可以通过将用于读取和写入的代码移动到它们自己的函数来简化循环。

while ( myfile >> x )
  std::cout << x << std::endl;

为了使用上述功能,您需要重载operator>>函数和operator<<函数,如下所示:

std::istream& operator>>(std::istream& in, student& s);
std::ostream& operator<<(std::ostream& out, student const& s);

我会把它留给你进行下一步。