Using Loop to Read from File

I am using the following function to load my parallel arrays from the information in a file. The file consists of 5 columns and 10 rows. Each column is filled with random numbers (1-65) and are separated by only tabs. When I call this function then output the arrays, the first number in the file is completely skipped and the second and third values are switched.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  int loadArrays(int playerNum[], int hits[], int atBats[], int runs[], int rbis[], double batAvg[], int SIZE)
{
	
	ifstream inputFile;
	inputFile.open("playerstats.txt");

	short i = 0;
	while (inputFile >> playerNum[i])
	{
	inputFile >> playerNum[i] >> atBats[i] >> hits[i] >> runs[i] >> rbis[i];
	i++;
	}

	return (i + 1);
	
}


** UPDATE**

I figured out why the 2nd and third number are switched. (I the arguments that I was passing and the parameters were switched). Still trying to figure out how to fix the read position problem.

Last edited on
Can you show the file?
10 36 25 2 5
2 12 5 0 1
34 18 7 1 0
63 41 20 4 2
12 10 3 1 0
14 2 1 1 1
27 55 27 10 8
8 27 12 3 4
42 32 8 2 1
33 19 4 1 0

That's all just in a txt file. I don't see a way to attach it here. Forgive me if there is, this is my first time using this site.
Look at this snippet:
1
2
3
	while (inputFile >> playerNum[i])
	{
	inputFile >> playerNum[i] >> atBats[i] >> hits[i] >> runs[i] >> rbis[i];

You're trying to read playerNum[] twice. Once in the while() and once in the body of the while.
I suggest:
1
2
3
	while (inputFile >> playerNum[i] >> atBats[i] >> hits[i] >> runs[i] >> rbis[i])
	{
	...
That results in the following being loaded in:

2 12 5 0 1
63 41 20 4 2
14 2 1 1 1
8 27 12 3 4
33 19 4 1 0

It is skipping every other line instead of the first digit.

while (inputFile >> playerNum[i])

So it appears this code is moving my read position every time it loops. Is there a way that I can move the read position back or is there a better way for me to test if there is still contents in the file?
Last edited on
It is skipping every other line instead of the first digit.

Did you remove the line in the body of your loop? The only thing that should be in the body of the loop is the incrementing of the index variable.

Oh wow! That worked.

Thank you so much!!
Topic archived. No new replies allowed.