【发布时间】:2016-12-31 12:10:22
【问题描述】:
在开始之前,我必须首先说我已经研究过这个错误的可能解决方案。不幸的是,它们都与不使用数组有关,这是我的项目的要求。另外,我目前正在学习 CS 入门,所以我的经验几乎没有。
数组的目的是从文件中收集名称。因此,为了初始化数组,我计算名称的数量并将其用作大小。问题是标题中所述的错误,但我在仍然使用一维数组时看不到解决方法。
main.cpp
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <iostream>
#include "HomeworkGradeAnalysis.h"
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("./InputFile_1.txt");
outfile.open("./OutputfileTest.txt");
if (!infile)
{
cout << "Error: could not open file" << endl;
return 0;
}
string str;
int numLines = 0;
while (infile)
{
getline(infile, str);
numLines = numLines + 1;
}
infile.close();
int numStudents = numLines - 1;
int studentGrades[numStudents][maxgrades];
string studentID[numStudents];
infile.open("./InputFile_1.txt");
BuildArray(infile, studentGrades, numStudents, studentID);
infile.close();
outfile.close();
return 0;
}
HomeworkGradeAnalysis.cpp
using namespace std;
void BuildArray(ifstream& infile, int studentGrades[][maxgrades],
int& numStudents, string studentID[])
{
string lastName, firstName;
for (int i = 0; i < numStudents; i++)
{
infile >> lastName >> firstName;
studentID[i] = lastName + " " + firstName;
for (int j = 0; j < maxgrades; j++)
infile >> studentGrades[i][j];
cout << studentID[i] << endl;
}
return;
}
HomeworkGradeAnalysis.h
#ifndef HOMEWORKGRADEANALYSIS_H
#define HOMEWORKGRADEANALYSIS_H
const int maxgrades = 10;
#include <fstream>
using namespace std;
void BuildArray(ifstream&, int studentGrades[][maxgrades], int&, string studentID[]);
void AnalyzeGrade();
void WriteOutput();
#endif
文本文件格式简单:
Boole, George 98 105 0 0 0 100 94 95 97 100
每一行都是这样,有不同数量的学生。
还有什么方法可以让我在使用数组的同时仍然可以流式传输学生的姓名?
【问题讨论】:
-
您考虑过使用
vector吗? -
我在其他解决方案之一中看到了矢量,但我还没有学会它。我尝试使用它,但我不太了解它,所以我无法让它工作。抱歉,将代码编辑为原来的样子。这是 studentID[numStudents],但这就是错误的原因。
-
您最好尝试让向量工作并发布有关向量的问题...
-
即使您不使用向量,您也可以将数组声明为具有比您需要处理的输入大的固定数量的元素。这不是好的编程实践(学习
vector<>和push_back()等会好得多),但它会解决这个任务。 -
我想我会用它作为最后的手段。我还在尝试找出矢量解决方案。