Hi, I have a file in the format of:

First-Name Last-Name StudentNumber
Grade1
Grade2
Grade3


Any student may up to 10 grades, and I want to read the information from the text file into a vector.

My question is, how can I read the file into the vector so that the grades are put into the vector as grades and not the student names or numbers (In other words, so everything is kept in order.)

My problem is that the number of grades a student may have is unknown and inconsistant. Any help would be greatly appreciated!

Thanks!

(what I have at the the moment is this)

if (theFile.is_open())
{ // Yup, it's open
StudentData data;
while(!theFile.eof())
{
theFile >> data.first >> data.last
>> data.number; (What to do about the grades?)


vecStudents.push_back(data);
}
}

Recommended Answers

All 5 Replies

You could always make a loop that keeps going until theFile >> grade fails. When this happens, clear the errors with

theFile.clear();

and read in some more names, enter the grade loop again, etc.

The more-robust method is to use getline to read each line into a string, and if there are any non-numeric characters in it, count it as a name.

Use getline() to read each line. If the line does not start with a digit, it's a name, store it. Otherwise convert to an integer and store it with the last name read.

>If the line does not start with a digit, it's a name, store it.
Ah, but what if there is a non-numeric character later on in the line? That's why I said, "If there are any non-numeric characters in it, count it as a name." However strange it sounds, I have heard of people that have numbers in their name.

>If the line does not start with a digit, it's a name, store it.
Ah, but what if there is a non-numeric character later on in the line? That's why I said, "If there are any non-numeric characters in it, count it as a name." However strange it sounds, I have heard of people that have numbers in their name.

Well,
1) reading the entire line prevents the obvious error when 33T is read as a score because of poor file proofreading...
2) when you meet 3v3lyn or 51Lv1a, you be sure to let me know...
:icon_twisted:

>when you meet 3v3lyn or 51Lv1a, you be sure to let me know...
I will, I will. :icon_biggrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.