reading in a unknown matrix from text file

Hi there,

I am currently trying to write a program that will let me read in an n x n matrix and then let me print it out again

a typical matrix will look like this

1,1
0,-1

could you please tell me why my code will not work at the minute.. It compiles but will not give me the desired output.

Thanks, Harry

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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  //Include the necessary packages
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
//Use the std namespace
using namespace std;
//Initiate the main program.
int main() {
	//Declare the necesarry variables.
	int n = 0;
	int i = 0;
	int line = 0;
	int element = 0;
	double tempval;
	string startstring, middlestring, endstring, aline;//create temporary strings to hold the data.
	vector <double> templine;//Create a temporary line vector to hold the data.
	vector <vector <double>> data;//create a vector of vectors to hold the data.
		ifstream myFile ("test_data.txt");//Open the file for reading.

		if(myFile.is_open()) {//If the file is open.
			cout << "File Opened\n";//Tell the user the file opened.
		
		

		while(!myFile.eof()) {//While not at the end of the file.
			
			getline (myFile,aline);//Put the current line into a string. 

			int comma_pos = aline.find(',',0);//Find the first comma in the line.
			int nextcomma = aline.find(',',comma_pos+1);//Find the comma after that.
			
			startstring = aline.substr(0,comma_pos);//Put the first value into a string.
			tempval = atof(startstring.c_str());//Put the string into a double.
			templine.push_back(tempval);//Push the double into a vector.

		
			while  (aline.find(',',comma_pos) != -1) {//While not on the last comma.

				comma_pos = aline.find(',',0);
				nextcomma = aline.find(',',comma_pos+1);
				middlestring = aline.substr(comma_pos+1,nextcomma);
				tempval = atof(middlestring.c_str());
				templine.push_back(tempval);
			
		
			endstring = aline.substr(comma_pos+1, aline.length()-1);
			
			data.push_back(templine);
			n++;
			}
		}
		}

		
		else {//If the file did not open.
			cout << "File unable to be opened\n";
			exit(1);//Tell the user and exit.

		}
		

		myFile.close();


		for ( i = 0; i < n; i++ )  {

		ofstream outfile("inverted_Matrix.txt");

		if(outfile.is_open()) {
			cout << "File opened for writing\n";
		}
		else {
			cout << "File unable to be opened for writing\n";
		exit(1);
		}
		for (i = 0; i < data.size(); i++) {
		outfile << setprecision(2) << fixed << data[i][0] << " " << setprecision(3) << data[i][1] << endl;
		}
		}
	return 0;
}
Topic archived. No new replies allowed.