I'll give you some hints - this is probably more like CodeReview.SE now...
I would recommend
- separating the reading from printing
- treating the grades as numbers (e.g.
int
or double
) so you can actually work with them, and have some validation that you're not reading non-sense
- Use idiomatic loops, don't just
if (infile.good())
- e.g. you can't tell whether you've reached end-of-file before you try to read
Fixing up the interface, I'd suggest something like this
struct Grade {
void readInput(std::string fname);
void print(std::ostream& os = std::cout) const;
private:
static constexpr auto max_line_length = std::numeric_limits<ssize_t>::max();
std::vector<int> grades;
};
Note that readInput
reads into grades
without printing anything. Note also that it takes the name of the file to read as the argument, instead of hardcoding some filename.
int main() {
Grade grading;
grading.readInput("grades.txt");
grading.print();
}
This would be the main program.
The simplified/extended version of readGrades
could be:
void Grade::readInput(std::string fname) {
std::ifstream infile(fname);
infile.ignore(max_line_length, '\n'); // ignore the first line
int grade = 0;
while (infile >> grade) {
grades.push_back(grade);
infile.ignore(max_line_length, '\n'); // ignore rest eating newline
}
}
Note how we ignore lines or parts thereof that we are not interested in. For extra control consider disabling white-space skipping:
infile >> std::nowskipws;
The print function could be a simple:
void Grade::print(std::ostream& os) const {
os << "Grades:";
for (int g : grades) {
os << " " << g;
}
os << std::endl;
}
Full Demo
Live On Coliru
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
struct Grade {
void readInput(std::string fname);
void print(std::ostream& os = std::cout) const;
private:
static constexpr auto max_line_length = std::numeric_limits<ssize_t>::max();
std::vector<int> grades;
};
int main() {
Grade grading;
grading.readInput("grades.txt");
grading.print();
}
void Grade::readInput(std::string fname) {
std::ifstream infile(fname);
infile.ignore(max_line_length, '\n'); // ignore the first line
int grade = 0;
while (infile >> grade) {
grades.push_back(grade);
infile.ignore(max_line_length, '\n'); // ignore rest eating newline
}
}
void Grade::print(std::ostream& os) const {
os << "Grades:";
for (int g : grades) {
os << " " << g;
}
os << std::endl;
}
Prints
Grades: 12 17 1 29
Given grades.txt
:
Ignore the first line
12
17
1
29