将数据文件读入结构 C++

  • 本文关键字:结构 C++ 数据 文件 c++
  • 更新时间 :
  • 英文 :


我正在尝试将此数据文件读入结构。 但是我这样做有问题。 这是我到目前为止的代码。我遇到问题的部分是读取数据函数

#include<iostream>
#include<fstream>
#include<sstream>
#include<cstring>
#include<string>
using namespace std;
const int CAP = 100;
const int MAX_CHAR = 31;
int totalLines = 0;
struct Student
{
char name[31];
int score[10];
};
int readData(ifstream& iFile, Student list[]);
void findLowestEach(Student list[], int size);
void findHighestEach(Student list[], int size);
void calcAverage(Student list[], int size);
int main()
{
Student list[CAP];
ifstream inFile;
inFile.open("data.txt");
if (!inFile.is_open()) {
cout << "Error: File cannot be opened.n";
exit(1);
}
readData(inFile, list);
// calls all of the other functions
//readData(inFile, list[]);
//findLowestEach(list[], size);
//cout << endl;
//findHighestEach(scores, names);
//cout << endl;
//calcAverage(scores, names);
}
int readData(ifstream& iFile, Student list[])
{
int i = 0;
while (!iFile.eof())
iFile >> list[i].name;
for (int i = 0; i < 10; i++)
{
iFile >> list[i].score;
}
return 0;
}

这是数据文件

Bob 56 67 83 76 84 94 68 86 78 56
John 76 89 95 64 78 34 99 89 104 98
Joe 65 68 89 78 45 69 98 101 99 89
Amy 86 77 89 76 94 54 78 89 78 66
Nick 76 69 95 94 78 64 99 89 110 88
Alex 95 88 89 78 95 69 88 101 99 89
Marga 96 67 89 76 64 94 98 83 78 56
Mike 76 89 95 64 78 34 99 89 104 98
Bella 85 68 89 78 45 69 98 101 99 89
Priya 86 77 89 76 94 94 78 89 78 96
Karen 78 69 95 94 78 94 99 89 110 88
Amit 95 88 79 78 95 89 88 101 99 89

只是希望朝着读取数据文件的正确方向推动。我认为我走在正确的轨道上,但我不确定

我不确定你到底有什么问题。但是如果你想用C++编写这段代码,我的建议是:

  1. 不要在学生结构中使用char name[31]。您应该使用std::string.如果您使用的是 C 样式字符串,则必须自己管理以处理复制内存并确保数组足够大以处理输入中的所有数据。使用 std::string,您不会遇到此问题,operator>>可以正常工作。

  2. 我建议使用std::vector作为学生结构的容器。由于它是标准库容器,您可以在标准库的其他函数中使用它来排序或查找一些元素。

工作代码如下。

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
static constexpr int CAP = 100;
struct Student
{
std::string name{};
int score[10] = {};
};
std::vector<Student> readData(ifstream& iFile);
void findLowestEach(Student list[], int size);
void findHighestEach(Student list[], int size);
void calcAverage(Student list[], int size);
void printStudents(const std::vector<Student> &a_vector);
int main()
{
ifstream inFile;
inFile.open("text.txt");
if (!inFile.is_open()) {
cout << "Error: File cannot be opened.n";
exit(1);
}
printStudents(std::move(readData(inFile)));
}
void printStudents(const std::vector<Student> &a_vector) {
for(const auto & s: a_vector) {
std::cout << s.name << " ";
int i = 0;
while( i < 10) {
std::cout << s.score[i] << " n";
i++;
}
std:: cout << std::endl;  
}
}
std::vector<Student> readData(ifstream& iFile)
{
std::vector<Student> students;
int i = 0;
while (!iFile.eof()) {
Student student{};
iFile >> student.name;
for (int i = 0; i < 10; i++)
{
iFile >> student.score[i];
}
students.push_back(student);
}
return students;
}

我的结论是,如果您正在使用C++请使用标准的库容器和算法。这将使您更轻松地编写代码。

最新更新