How To Read A .dat File

Hey everyone I'm working on a program that reads from a .dat file that has names and numbers associated with the name. What the big picture it will be able to take those names and numbers find the avg of certain peoples scores and display these numbers or names who have the highest etc.
So to keep this short in my main I have it call the class and pass "Even.dat" as a char * fname my questions is how do I go about reading this .dat file? I know sorting it will use a sort algorithm which I will be using a bubble sort. But I haven't worked with ofstream and ifstream very much so some tips would be great! Here's an example of what the .dat file contains

1
2
3
4
5
6
David                  42
Rebecca                83
Jonathan               79
Matthew                77
Rose                    7
Melanie                75


1
2
3
4
5
int main()
{
   StudentStat StatEven("Even.dat");
   return 0;
}


1
2
3
4
5
6
7
8
9
10
StudentStat::StudentStat(char * fname)
{
	Avg = StDev = Median = -1.0;  // Initialize values before reading
	Size = 0;
    
	// TODO: READ DATA FROM INPUT FILE

	// Sort the names/scores in descending order using bubble sort
	Sortem();
}
Last edited on
Will the names ever have spaces?
No they won't ever have spaces, it will either output the name if they have the highest average or it will show the number. It will always just be the first name. Unless you consider the spaces between the name and number?
Last edited on
OK then, you can just use the >> operator to read the name into a std::string and the number into an int, then add them to a std::map.
could you elaborate a little on the std::map? I've never done anything using inputting or outputting a file before. Also how do I go about running through the file and no how to split the name with the numbers?

Also let me explain a little more of the program so the function I posted up top will read the input file and store it in an array I'm guessing? Because it will then go to a bubble sort to separate name and scores then there are function called get name and get score that takes an int index in the parameter. So separating them in an int and string like you mentioned would that still be ideal?
Last edited on
Could you elaborate on the restrictions of your assignment? If you're not allowed to use certain things or you have to do it in a certain way, we need to know.
Read up!

http://www.cplusplus.com/doc/tutorial/files/

Here is a great example of the use of a map:
http://kengine.sourceforge.net/tutorial/g/stdmap-eng.htm

The basic idea of a map is that there is a key and there is a value; the key corresponds to the value. To create a map: std::map<type one, type two> MapName;. So if you have the key be an std::string, and the value be an int, you can correspond a string to an int.
Topic archived. No new replies allowed.