Reading text file (having integers) into an array in C++

Hi Guys, I am new to C++. I would really appreciate if you could help me with this problem...

Here is a sample text file. The first line contains two numbers which have to read first and they will determine how many rows and columns would be there in subsequent file. For eg: here we have 3 4 in the first line ( separated by space) and we have 3 rows and four columns after that. I want to read the first line to get to know how big array I should create to read the remaining lines. Then, rest of the file (except the last line) has be stored on another array ( containing 0 and 1). Finally, the last line has be read separately into a third array.

3 4
1 0 0 0
1 1 0 1
1 0 1 0
0 2 1 0 1 1

Here is what I have done so far. I don't think this is the most efficient way to do, but It works for the first two numbers. But after that it doesn't work. Please take a look and see if you can help:



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
64
65
66
67
# include <iostream>
# include <fstream>
# include <string>

using namespace std;

int main (){
	char fName[20]; 
    char buff1[8]; 	char buff2[8];

	// Asking user for the file name and storing it

	cout <<"Enter the file name" << endl;
	cin >> fName ; 
	ifstream qFile(fName);
		
	// Checking if the file is good
	
	if (!qFile.good()){
		cout << "Error reading the file"<< endl; 
		return 1;
	}

	// Reading the number of switches and light bulbs 

	qFile.getline(buff1,8,' ');
	qFile.getline(buff2,8,' ');

// Printing out the first two numbers to confirm if the code is right.

	for( int i = 0; i< 2; i++){
		cout << buff1[i] ;
	}

	cout <<endl;

	for( int i = 0; i< 2; i++){
		cout << buff2[i] ;
	}

	cout <<endl;

	// Converting the string to integet (to determine the size of the array)

	int dim1 = atoi (buff1);
	int dim2 = atoi (buff2);

	// Reading the next set of lines into the second array

	int* test; 
	test = new int [dim1*dim2];
	for (int i = 0; i< dim2; i++)
	{
	for (int j = 0; j < dim1; j++)
		{
		qFile.getline(buff1,8,' ');
		test[i*dim1+j] = atoi(buff1);
		cout << test [i*dim1+j];
		}
	cout <<endl;
        }
	// Reading the last line until you find eol 
        qFile.close();
	return 0;

	
}

Last edited on
Topic archived. No new replies allowed.