Я пытаюсь прочитать этот файл данных в структуру. однако у меня проблемы с этим. вот код, который у меня есть до сих пор. часть, с которой у меня проблемы, - это функция readData
#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
Просто надеюсь на толчок в правильном направлении для чтения в файле данных. Я думаю, что я на правильном пути, но я не уверен
1 ответ
Я не уверен, какая именно проблема у вас есть. Но если вы хотите написать этот код на C++, мои предложения таковы:
Не используйте
char name[31]
в структуре ученика. Вы должны использоватьstd::string
. Если вы используете строки в стиле C, вы должны сами справиться с копированием памяти и убедиться, что массив достаточно велик для обработки всех данных на входе. С std::string у вас не будет этих проблем, иoperator>>
будет работать правильно.Я предлагаю использовать
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++, используйте стандартные контейнеры и алгоритмы библиотеки. Это облегчит вам написание кода.
Похожие вопросы
Связанные вопросы
Новые вопросы
c++
C++ — это язык программирования общего назначения. Изначально он разрабатывался как расширение C и имел аналогичный синтаксис, но теперь это совершенно другой язык. Используйте этот тег для вопросов о коде, который будет скомпилирован с помощью компилятора C++. Используйте тег версии для вопросов, связанных с конкретной стандартной версией [C++11], [C++14], [C++17], [C++20] или [C++23]. и т.д.