Reading arrays from file

Hi everyone, im new at programming and im sort of stuck at this bit and it keeps coming up with errors, while it does compile, its not displaying what i want.

i have a text file which contains a series of numbers:

1 2
3 4
5 6
7 8
9 3

and i am trying to put this into 2 arrays. The first column into double xArray[200], the the second into yArray[200]; then display them.

This is what i got:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int readfile(double x[], double y[], string name);
void printArray(double arg[], int length);

int main()
{
     double xArray[200], yArray[200];
     double *xArray_p = xArray, *yArray_p = yArray;
     int rows = 0;

     rows = readfile(xArray_p, yArray_p, "SampleSet.txt")
     printArray(xArray, rows);
     printArray(yArray, rows);

     return 0;
}

int readfile(double x[], double y[], string name)
{
	ifstream inFile;
	inFile.open("Sample.txt");
	int findRows = 0;
	string line;

	if(inFile.fail())
	{
		cout << "ERROR......... Failed to read from file" << endl;	
	}
	else
	{
		cout << "Reading from File........." << endl;
               
                while( getline( inFile, line, '\t' ))
			findRows++;

		for(int i = 0; i < findRows; i++)
			{
				inFile >> x[i], >> y[i];
			}	

		for(int i = 0; i < findRows; i++)
		{
			cout << x[i] << " " << y[i] << endl;
		}
	}

	inFile.close();					
        return findRows;
}

void printArray(double arg[], int length) 
{
  for (int n=0; n<length; n++)
    cout << arg[n] << " ";
  cout << "\n";
}


But everytime i run it it comes up with all these other characters and numbers, i know i did something wrong but i dont know what.

Could you guys please give me some feedback on what im doing wrong.
Thank you. :D

Last edited on
getline() advances the file pointer, so you'll need to reset to the beginning of the file before you try to read like you are on line 44 or you'll already be at the end of the file and get nothing.
thanks Zhuge for the reply.

Instead of using rewind() i opted to close and open the file again.
While it does work, to get the results i want, i was wondering would that result in any complications later on?

Furthermore i noticed that using:
1
2
while( getline( inFile, line, '\t' ))
       findRows++;


results in an extra row, i did a quick fix using findRows-- to get one less row.
Is there something i did wrong in that bit of code to get that? (i know i did something wrong)

Thanks.
Last edited on
Topic archived. No new replies allowed.