I’m having trouble coding part of a program that will read in a name and 10 numbers from a file. The fie is called grades.dat The structure of the data file is:
Number One
99 99 99 99 99 99 99 99 99 99
John Doe
90 99 98 89 87 90.2 87 99 89.3 91
Clark Bar
67 77 65 65.5 66 72 78 62 61 66
Scooby Doo
78 80 77 78 73 74 75 75 76.2 69
This is all I have for the function to get the data and I’m not even sure if that’s right.
void input (float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname)
{
ifstream infile;
infile.open ("grades.dat");
if (infile.fail())
{
cout << "Could not open file, please make sure it is named correctly (grades.dat)" << "\n" << "and that it is in the correct spot. (The same directory as this program." << "\n";
exit(0);
}
getline (infile, studentname);
return;
}
Use the standard C++ idiom, reading two lines at a time (or failing if this isn’t possible):
Note: If the sole purpose of he inner loop (marked
#1) is to store all the grades, then as @Rob suggests you can use stream iterators:The stream iterator does the same thing as the inner
whileloop above, i.e. it iterates over tokens of typedouble. You might like to insert the entire vector into a large container that holds pairsstd::pair<std::string, std::vector<double>>of names and grades.