reading in multiple files

I have a project completed where i read in a file and assigns the data in the txt file to a matrix. The problem i am having is that i have 8 data files named data1.txt through data8.txt. I need to find a way to loop through the the data file names by somehow incrementing the number portion of the filename.

here is the segment of code that it will be placed.

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
#include <iostream>
#include <fstream>
#include "magicSquare.h"

using namespace std;

int main () {
  int N;
  bool flag;

  //Open data files to read in data
  ifstream myfile ("data1.txt");

  if (myfile.is_open())
  {
	  //read in the size of the matrix
	  myfile>>N;

	  //declare double pointer matrix
	  int **matrix = new int*[N];

	  //Allocate Memory
	  for(int i = 0; i < N; i++){
		  matrix[i] = new int [N];
	  }

	  //make sure fileis not at end and read int the contents into the array matrix
	  while(myfile.good()){
		  for(int i = 0; i < N; i++){
			  for(int j = 0; j <N; j++){
		  myfile>>matrix[i][j];
			  }
		  }
	  }

does anyone know how i can loop through the data files to read them all in?
If you need anymore details about the project just let me know.
Okay, try putting the file name in a char array, and then you can iterate through each like this:
1
2
3
4
5
6
7
8
char filename[5];
for(int i = 0; filename[i] != '\0'; i++)
    filename[i] = '\0';
for(int i = 0; i <= 8; i++) {
    filename = "file" + (i + '0');
    ifstream myfile(filename);
    /* do you stuff now */
}

I haven't compiled this, but this is the basic idea :)
Last edited on
im getting an error on
filename = "data" + (i + '0');

it says char filename[5]
error: expression must be a modifiable lvalue

is the [5] supposed to be the size of the array?
Last edited on
http://www.cplusplus.com/doc/tutorial/arrays/

And yes to your last question. I assumed you knew how to use them seeing as they're all over your previous program :/
Last edited on
Topic archived. No new replies allowed.