Reading arrays from text file

Hello everyone this is my first post here as newly registered on this site

Anyways, I have a problem with my c++ code reading from a textfile

Here's my code:

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
#include<iostream>
#include<cmath>
#include<fstream>

using namespace std;


int main()
{
	ifstream readingfile;
	char file[100];
	int xarray[200];
	int yarray[200];

	cout<<"Enter the name of your file\n";
	cin>>file;
	cout<<"Reading data from the file\n\n";
	readingfile.open(file);
	if(!readingfile)
		cout<<"Error reading the file\n";

	double num_elements=sizeof(xarray)/sizeof(xarray[0]);

	for(int row=0;row<num_elements&&readingfile;row++){
	
			for(int column=0;column<num_elements&&readingfile;column++){

			readingfile>>xarray[row];
			readingfile>>yarray[column];
			cout<<xarray[row];
			cout<<"\t";
			cout<<yarray[column];
			cout<<endl;
		}
		
	}
	
	

}


Basically Im trying to see if I could display a set of numbers from a textfile(2 columns,number of rows varies)but its displaying an extra line of random set of numbers

Here is my sample textfile i want to read:

5 20
4 40
4 20
9 8
7 7
6 2
20 14

Here is what is displayed when i run the program:

5 20
4 40
4 20
9 8
7 7
6 2
20 14
20 -858993460

Any help would be much appreciated. Thanks!
Instead of a for loop, I would suggest a while loop...

1
2
3
4
5
6
7
8
9
10
	while(!readingfile.eof()){
	
			readingfile>>xarray[row];
			readingfile>>yarray[column];
			cout<<xarray[row];
			cout<<"\t";
			cout<<yarray[column];
			cout<<endl;
		}
         }


Unless you're expecting gibberish to be tossed at it, that should work fine.

Thanks, im actually going to build a function populating arrays then to calculate formulas

im just trying to figure this part out (which works now, thanks again), taking one step at a time, im so new to this c++ stuff, i spend lot of time doing trial and errors learning from tutorials online, textbook and other resources
Um, now im having trouble with the file checking
the program puts out endless lines when the file doesnt exist, can you help me with the file checking

thanks

edit: nvm i got it
Last edited on
Topic archived. No new replies allowed.