read from file algorithm

I have this code to read numbers from a file and put them into an array. but i have a problem which i cannot solve. can you help me please
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
  // fileToArray function is the function that is used for reading the file which's name, directory and path is taken as a parameter, and an array is taken as parameter to
// put the elements of array in it. And the array given as input is edited with respect to the given file. Array is taken as one dimensional array and other functions are
// written according to this condition and functioning of the other functions are explained in their explanations. Also, realloc function is used in this function for 
// incrementing the size of array by one double if needed to avoid using more memory than needed.
int fileToArray (string name, double arr[]) 
{

	string line, str = "" ; // line is the string that lines of the file are read by using getline built-in function and str is the string to read numbers
	//between whitespaces
	int arr_index = 0, row_counter = 0 ; // two integers are initialized to 0 to record the current index of array and count the number of rows of the matrix.
	ifstream file (name.c_str()) ; // file which's name is contained in string "name" is opened.
	if (file.is_open()) // this code block work in the case that the file is successfully opened.
	{
		while(getline(file,line)) // if getline function can read lines from the function into string called "line", the following block works. 
		{
			int string_index = 0 ; // string index is used for indexing the line read from file and initialized to 0 for every new line 
			row_counter ++ ; // row counter is incremented by 1 for every new line since every new line represents a row of matrix or vector
			while (1)
			{
				if (line[string_index] != ' ' && line[string_index] != '\0' && line[string_index] != '\n' ) // the case that string index is consist of the 
				//numerical values or "." that is used for floating number
				{
					str += line[string_index] ; // the character in the given index is appended to another string called "str"
					string_index ++ ; // string index is incremented by 1 to read the consecutive character of the string "line".
				}
				else if (line[string_index] == ' ') // the case that character of the current index is space, in that case the numerical values that are read
				//until that moment are passed to an index of the array
				{
					stringstream (str) >> arr[arr_index] ; // by using the built-in function of <sstream> library to get numerical values from string to a 
					//numerical variable
					str = "" ; // string is initialized to empty string to read the next double number
					arr_index ++ ; // array index is incremented by 1 to read the consecutive number from the string "str"
					realloc (arr, (arr_index + 1) * sizeof (double)) ; // array's size is incremented by size of one double for having memory for the next element.
					string_index ++ ; // string index is incremented by 1 to read the consecutive character of the string "line".
				}
				else // the case that character of the current string index is null or next line character
				{
					stringstream (str) >> arr[arr_index] ; // by using the built-in function of <sstream> library to get numerical values from string to a 
					//numerical variable
					str = "" ; // string is initialized to empty string to read the next double number
					arr_index ++ ; // array index is incremented by 1 to read the consecutive number from the string "str"
					if (line[string_index] != '\0')
						realloc(arr, (arr_index + 1) * sizeof (double)) ;// if element of the string is not '\0' ('\n' in this case), size of the array must be 
						//incremented by 1 for the next number in the file. if the element is equal to '\0', that means there is no more number in the file and therefore
						//we do not need to increment the size of array by 1.
					break ; // if the index is the end of the line, which is defined by '\n' or '\0' character, we need to get to the upper while loop either to
					// read a new line into array (in case of the character is '\n') or end reading from the file(in case of character '\0', so the break command 
					// is put to implement the either case.
				}
			}
		}
		cout << "SUCESS FAR"  ;
		return row_counter; // number of rows is returned as output	
	}
	else // in the case that the file cannot be opened, the error given below is throwed to the command line.
	{
		cout << "Unable to open file..." << '\n' ; // error message to be throwed in case of opening file operation is failed.
		return -1 ; // in case of unsuccessfull opening operation, impossible situation which is row number to be -1 is returned, and in the main and other function,
		//code is edited for this case.
	}
}
Hello azizcoktu,

While I look at your function it would help if you would post the input file, or at least a good sample, so that everyone will know what it looks like and can use the same information.

Also code that can be compiled helps. May not need all of it, but enough to make it work.

I can only guess at what header files you are using and I do not feel that I have all of them that are needed.

Lastly it helps to know what IDE/compiler you are using and what C++ standard you are using.

Andy
> int fileToArray (string name, double arr[])
If you want this to be C++, then make it
int fileToArray (string name, vector<double> &arr)

Because your attempt at using realloc is broken.
> realloc (arr, (arr_index + 1) * sizeof (double))
1. realloc returns a result.
2. realloc can return NULL
3. realloc can move the memory to somewhere else (which will disappoint the caller, because they won't see that).

In other words, like this
1
2
3
4
5
6
7
void *temp = realloc( arr, (arr_index + 1) * sizeof (double));
if ( temp ) {
    arr = temp;
    arr_index += 1;
} else {
    // do something with the unchanged arr, which was NOT extended.
}




And you need to have called fileToArray with a valid pointer to begin with.
Like
1
2
double *arr = NULL;
fileToArray("somefile",arr);


Not this - especially not this!
1
2
double arr[10];
fileToArray("somefile",arr);

You can't realloc an array!

> return row_counter; // number of rows is returned as output
Why not array_index?
Because if you have more (or less) than exactly one number per line, these two values are going to be distinct. You seem to be going to an awful lot of trouble to find spaces in a line, when the insertion operator does it all for you.

1
2
3
4
5
6
while(getline(file,line)) {  // read each line
  stringstream ss(line);
  while ( ss >> var ) {  // read each number on a line
    arr.push_back(var);  // when you've changed the 2nd parameter to be a vector reference.
  }
}

Hey Andy, thanks for your reply. I could not add the whole code here since it is long; therefore, the whole code is here in repl.it
https://repl.it/@Aziz_MuratMurat/ElasticMammothScreenscraper

I use DevC++ as compiler and it uses TDM G.C.C 4.9.2 64 bit release i guess

the sample file is
A.txt contains the matrix A and b.txt contains the vector b.
Then the code does the gaussian elimination by partial pivoting method to solve the vector x in equation Ax = b. If A is 2 by 2, then the condition numbers at infinity and one are calculated and printed out in the command line.
Thank you.
Aziz
Last edited on
And Salem, I will try to rearrange the function as you say. Thank you
Aziz
Hi, azizcoktu. Could you please post your A.txt and b.txt files, at least partially?
I’d like to test and debug the following method to read from them:

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>


template <typename T> struct BasicDynArr;
template <typename T>
std::ostream& operator<< (std::ostream&, const BasicDynArr<T>&);


template <typename T> struct BasicDynArr {
    int size {};
    int capacity {};
    T* arr { nullptr };
    int rows {};

    explicit BasicDynArr( int = 0 ) noexcept;
    BasicDynArr( const BasicDynArr& ) = delete;
    BasicDynArr& operator= ( BasicDynArr ) = delete;
    BasicDynArr( BasicDynArr&& ) = delete;
    BasicDynArr& operator= ( BasicDynArr&& ) = delete;
    ~BasicDynArr();
    void double_me();
    void push_back( T );

//friend:
    friend std::ostream& operator<< <>(std::ostream&, const BasicDynArr<T>&);
};


template <typename T> BasicDynArr<T>::BasicDynArr( int size_arg ) noexcept
    : size { size_arg }
    , capacity { size }
    , arr { new T[capacity] {} }
{
}


template<typename T> BasicDynArr<T>::~BasicDynArr()
{
    delete [] arr;
}


template <typename T> void BasicDynArr<T>::double_me()
{
    if ( !capacity ) {
        capacity = 1;
        arr = new T[capacity] {};
        return;
    }

    capacity *= 2;
    T* tmp { new T[capacity] {} };
    for (int i {}; i < size; ++i) {
        tmp[i] = arr[i];
    }
    delete [] arr;
    arr = tmp;
}


template <typename T> void BasicDynArr<T>::push_back( T val )
{
    if (size == capacity) {
        double_me();
    }
    arr[size++] = val;
}


template <typename T>
std::ostream&
operator<< (std::ostream& os, const BasicDynArr<T>& rhs)
{
    for (int i {}; i < rhs.size; ++i) {
        if ( i % rhs.rows ) {
            std::cout << '\n';
        }
        std::cout << rhs.arr[i] << ' ';
    }
    return os;
}


int fileToArray ( std::string name, BasicDynArr<double>& bda )
{
    std::ifstream file (name) ;
    if (!file) {
        std::cout << "Unable to open file...\n" ;
        return -1 ;
    }

    for(std::string line; std::getline(file, line); /**/) {
        ++ bda.rows ;
        std::istringstream iss { line };
        for (double d; iss >> d; /**/) {
            bda.push_back(d);
        }
    }
    std::cout << "SUCCESS FAR\n"  ;
    return bda.rows;
}


int main ()
{
    std::cout << "Please enter the name of the file that contains the matrix A\n"
                 "(in full detail)\n>>> " ;
    std::string nameA ;
    std::cin >> nameA ;
    BasicDynArr<double> bda_a;
    if (-1 == fileToArray(nameA, bda_a)) {
        // Cannot open file
        return 0;
    }
    std::cout << "First array:\nNumber of lines: " << bda_a.rows << '\n'
              << bda_a << '\n';

    [[maybe_unused]] double* arrA { bda_a.arr };

    std::cout << "\nPlease enter the name of the file that contains the vector b"
                 "\n(in full detail):\n>>> " ;
    std::string nameb;
    std::cin >> nameb ;
    BasicDynArr<double> bda_b;
    if (-1 == fileToArray(nameb, bda_b)) {
        // Cannot open file
        return 0;
    }
    std::cout << "First array:\nNumber of lines: " << bda_b.rows << '\n'
              << bda_b << '\n';

    [[maybe_unused]] double* arrb { bda_b.arr };

    return 0 ;
}

Last edited on
Hi, Enoizat.
A.txt contains :
3.1400 1.5900 2.6500 3.5800
9.7900 3.2300 8.4600 2.6400
3.3800 3.2700 9.5000 2.8800
4.1900 7.1600 9.3900 9.3700

and b.txt contains :
5.1000
5.8200
0.9700
4.9400

thank you.
Last edited on
I have no notion of the gaussian elimination algorithm, so I assume you know what you’re doing.
The question is why you reject the standard library, which would make your code so better readable and would cut back errors?
I’ve seen people worried about (presumed) performance issues with std::vectors, but I can’t believe there’s really any need to rewrite std::max() and std::abs().

So my real advice is
a) ignore my BasicDynArr class and simply use std::vector;
b) in general, rely on standard library;

c) remember you’ve recycled your "row_number" variable to store "arrb" rows number
In your comments I can read:
1
2
3
4
if (row_number == 2) // if matrix A is 2 by 2 matrix, condition numbers
                     // calculated in line 306 to 311 (also in the same if
                     // statement condition) are printed
                     // in this code block. 

"row_number", at that line, tells you about "vector b", not "matrix A" (anyway, in my example "row_number" has been replaced by a far clearer variable).

d) don’t forget C-style arrays decay into pointers when passed as function arguments.

e) Since what above, you usually need to pass the array dimensions together with your (now decayed) array to your functions.
Again, std::vector provide the at() method, which stops you when you cross the boundaries.

I’ve rewritten your code according to my style.
I hope someone would come and give better help.

It will take a couple of post to be entirely copied.

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <limits>
#include <sstream>
#include <string>
#include <utility>


template <typename T> struct BasicDynArr;
template <typename T>
std::ostream& operator<< (std::ostream&, const BasicDynArr<T>&);


template <typename T> struct BasicDynArr {
    int size {};
    int capacity {};
    T* arr { nullptr };
    int rows {};

    explicit BasicDynArr( int = 0 ) noexcept;
    BasicDynArr( const BasicDynArr& ) noexcept;
    BasicDynArr& operator= ( BasicDynArr ) noexcept;
    BasicDynArr( BasicDynArr&& ) noexcept;
    BasicDynArr& operator= ( BasicDynArr&& ) noexcept;
    ~BasicDynArr();
    void double_me();
    void push_back( T );

//friend:
    friend std::ostream& operator<< <>(std::ostream&, const BasicDynArr<T>&);
};


template <typename T> BasicDynArr<T>::BasicDynArr( int size_arg ) noexcept
    : size { size_arg }
    , capacity { size }
    , arr { new T[capacity] {} }
{
}


template<typename T> BasicDynArr<T>::BasicDynArr(const BasicDynArr& rhs) noexcept
    : size { rhs.size }
    , capacity { rhs.capacity }
{
    delete [] arr;
    arr = new T[capacity] {};
    for (int i {}; i < size; ++i) {
        arr[i] = rhs.arr[i];
    }
    rows = rhs.rows;
}


template<typename T>
BasicDynArr<T>&
BasicDynArr<T>::operator=(BasicDynArr rhs) noexcept
{
    using std::swap;
    swap( *this, rhs );
    return *this;
}


template<typename T> BasicDynArr<T>::BasicDynArr(BasicDynArr&& rhs) noexcept
    : size( std::exchange( rhs.size, size ) )
    , capacity( std::exchange( rhs.capacity, capacity ) )
    , arr( std::exchange( rhs.arr, arr ) )
    , rows( std::exchange( rhs.rows, rows ) )
{
}


template<typename T>
BasicDynArr<T>& BasicDynArr<T>::operator=( BasicDynArr&& rhs ) noexcept
{
    size = std::exchange( rhs.size, size );
    capacity = std::exchange( rhs.capacity, capacity );
    arr = std::exchange( rhs.arr, arr );
    rows = std::exchange( rhs.rows, rows );
}


template<typename T> BasicDynArr<T>::~BasicDynArr()
{
    delete [] arr;
}


template <typename T> void BasicDynArr<T>::double_me()
{
    if ( !capacity ) {
        capacity = 1;
        arr = new T[capacity] {};
        return;
    }

    capacity *= 2;
    T* tmp { new T[capacity] {} };
    for (int i {}; i < size; ++i) {
        tmp[i] = arr[i];
    }
    delete [] arr;
    arr = tmp;
}


template <typename T> void BasicDynArr<T>::push_back( T val )
{
    if (size == capacity) {
        double_me();
    }
    arr[size++] = val;
}


template <typename T>
std::ostream&
operator<< (std::ostream& os, const BasicDynArr<T>& rhs)
{
    int cols { rhs.size / rhs.rows };
    for (int i {}; i < rhs.size; ++i) {
        if ( i && !(i % cols) ) {
            std::cout << '\n';
        }
        std::cout << std::fixed << std::setprecision(4) << rhs.arr[i] << ' ';
    }
    return os;
}


int fileToArray ( std::string name, BasicDynArr<double>& bda );
int find_pivot (double * const arr, int row, int column);
void change_rows (double * const arr, int pivot, int row_number, int pivot_row);
void change_rows_b (double * const arr, int row1, int row2);
void elimination (double * const arrA, double * const arrb, int row_number);
void back_substitution (double * const arrA,
                        double * const arrb,
                        double * const arrx,
                        int row_number);
void inverse (double * const arr);
double max_2 (double num1, double num2);
double abs_udef (double num);
double cond_inf (double * const arr);
double cond_one (double * const arr);
bool is_singular (double * const arr, int row_number);
void arrayToFile (double * const arr, int row_number);


int main ()
{
    std::cout << "Please enter the name of the file that contains the matrix A "
                 "(in full detail)\n>>> " ;
    std::string nameA ;
    std::cin >> nameA ;
    BasicDynArr<double> bda_a;
    if (-1 == fileToArray(nameA, bda_a)) {
        std::cout << "\nPlease check the file name for matrix A...\n" ;
        return 0;
    }
    std::cout << "First array:\nNumber of lines: " << bda_a.rows << '\n'
              << bda_a << '\n';

    std::cout << "\nPlease enter the name of the file that contains the vector b"
                 " (in full detail):\n>>> " ;
    std::string nameb;
    std::cin >> nameb ;
    BasicDynArr<double> bda_b;
    if (-1 == fileToArray(nameb, bda_b)) {
        std::cout << "\nPlease check the file name for vector b...\n" ;
        return 0;
    }
    std::cout << "First array:\nNumber of lines: " << bda_b.rows << '\n'
              << bda_b << '\n';

    double condition_one {};
    double condition_inf {};
    if (2 == bda_b.rows) {  // this part will be skipped as for your files
        condition_one = cond_one(bda_a.arr);
        inverse(bda_a.arr);
        condition_inf = cond_inf(bda_a.arr);
    }

    elimination(bda_a.arr, bda_b.arr, bda_b.rows);
    if (is_singular(bda_a.arr, bda_b.rows)) {
        std::cout << "\nGiven matrix A is a singular matrix... \n" ;
    } else {
        double* arrx { new double [bda_b.rows] } ;
        back_substitution(bda_a.arr, bda_b.arr, arrx, bda_b.rows) ;
        arrayToFile(arrx, bda_b.rows) ;
        delete[] arrx ;
        if (bda_b.rows == 2) {
            std::cout << "\nCondition number at one is: " << condition_one
                      << "\nCondition number at infinity is: " << condition_inf
                      << '\n';
        }
    }
    return 0 ;
}
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/** Read the content of file 'name' into a BasicDynArr
 *  Returns -1 on failure (if file cannot be opened);
 *          the number of read elements otherwise.
 */
int fileToArray ( std::string name, BasicDynArr<double>& bda )
{
    std::ifstream file (name) ;
    if (!file) {
        std::cout << "Unable to open file...\n" ;
        return -1 ;
    }

    for(std::string line; std::getline(file, line); /**/) {
        std::istringstream iss { line };
        for (double d; iss >> d; /**/) {
            bda.push_back(d);
        }
        ++ bda.rows ;
    }
    std::cout << "SUCCESS FAR\n"  ;
    return bda.rows;
}


/** Partial pivoting algorithm implementation.
 * Returns the number of row where there is the largest number in a given column
 */
int find_pivot (double * const arr, int row, int column)
{
    int pivot {} ;                  // pivot of the given column
    double max = std::numeric_limits<double>::lowest() ;
    // Find the row where there is the largest number in a given column column
    // (== the pivot):
    for (int i = column; i < row; ++ i) {
        if (arr[ (i*row) + column ] > max ) {
            max = arr[ (i*row) + column ] ;
            pivot = i ;             // pivot = the row number
        }
    }
    std::cout << "SUCCESS PIVOT\n" ;
    return pivot ;
}


/** Performs a sequence of swaps on arr values
 */
// A better name would be swap_many_values
void change_rows (double * const arr, int pivot, int row_number, int pivot_row)
{
    for (int i {} ; i < row_number; ++ i) {
        double temp = arr[pivot * row_number + i] ;
        arr[pivot * row_number + i] = arr[pivot_row * row_number + i] ;
        arr[pivot_row * row_number + i] = temp ;
    }
    std::cout << "SUCCESS ROWSA\n" ;
}


/** Swaps two values
 */
void change_rows_b (double * const arr, int row1, int row2)
{
    double temp = arr[row1] ;
    arr[row1] = arr[row2] ;
    arr[row2] = temp ;
}


/** Gaussian elimination implementation.
 */
void elimination (double * const arrA, double * const arrb, int row_number)
{
    for (int column {}; column < row_number; ++ column ) {
        int pivot { find_pivot (arrA, row_number, column) } ;
        change_rows(arrA, pivot, row_number, column) ;
        change_rows_b(arrb, pivot, column) ;

        for (int j { column + 1 }; j < row_number; ++j) {
            double div {
                arrA[j * row_number + column] / arrA[column * row_number + column]
            };
            arrb[j] = arrb[j] - div * arrb[column] ;
            for (int k { column }; k < row_number; ++ k) {
                arrA[j * row_number + k] =   arrA[j * row_number + k]
                                           - div*arrA[column*row_number + k] ;
            }
        }

    }
    std::cout << "SUCCESS ELIM\n" ;
}


/** This function implements the algorithm to obtain the arrx, which is a
 *  solution to Ax = b equation.
 */
void back_substitution (double * const arrA,
                        double * const arrb,
                        double * const arrx,
                        int row_number)
{
    for (int i { row_number - 1 }; i >= 0; --i)  {
        arrx[i] = {} ;
        double sum {} ;
        for(int j { row_number - 1 }; j >= i ; --j) {
            sum += arrx[j] * arrA[i * row_number + j] ;
        }
        arrx[i] = ( arrb[i] - sum ) / arrA[i * row_number + i] ;
    }
}


/** Takes an array as input and change it to its inverse.
 */
void inverse (double * const arr)
{
    double det { ( arr[0] * arr[3] ) - ( arr[1] * arr[2] ) };
    double temp { arr [0] / det };
    arr[0] = arr[3] / det ;
    arr[3] = temp ;
    arr[1] *= (-1) / det ;
    arr[2] *= (-1)  / det ;
}


/** A funny version of std::max()...
 */
double max_2 (double num1, double num2)
{
    if (num1 >= num2) { return num1; }
    else              { return num2; }
}


/** A funny version of std::abs()
 */
double abs_udef (double num)
{
    if (num >= 0) { return num; }
    else          { return (-1) * num ; }
}


double cond_inf (double * const arr)
{
    double norm {
        max_2 ( abs_udef(arr[0]) + abs_udef(arr[1]) ,
                abs_udef(arr[2]) + abs_udef(arr[3]) )
    };
    inverse(arr) ;
    double norm_inv {
        max_2 ( abs_udef(arr[0]) + abs_udef(arr[1]) ,
                abs_udef(arr[2]) + abs_udef(arr[3]) )
    };

    return norm * norm_inv ;
}


double cond_one (double * const arr)
{
    double norm {
        max_2 ( abs_udef(arr[0]) + abs_udef(arr[2]) ,
                abs_udef(arr[1]) + abs_udef(arr[3]) )
    };
    inverse(arr) ; // arr is edited to become its inverse.
    double norm_inv {
        max_2 ( abs_udef(arr[0]) + abs_udef(arr[2]) ,
                abs_udef(arr[1]) + abs_udef(arr[3]) )
    };

    return norm * norm_inv ;
}


bool is_singular (double * const arr, int row_number)
{
    return arr[ row_number * row_number - 1 ] <= 0. ;
}


void arrayToFile (double * const arr, int row_number)
{
    std::ofstream myfile ("x.txt") ;
    if ( !myfile ) {
        std::cout << "Unable to open the file \" x.txt \" ... " ;
        return;
    }
    for (int i {}; i < row_number; ++i) {
        myfile << arr[i] << '\n' ;
        std::cout << arr[i] << '\n' ;
    }
}


Output:
Please enter the name of the file that contains the matrix A (in full detail)
>>> A.txt
SUCCESS FAR
First array:
Number of lines: 4
3.1400 1.5900 2.6500 3.5800
9.7900 3.2300 8.4600 2.6400
3.3800 3.2700 9.5000 2.8800
4.1900 7.1600 9.3900 9.3700

Please enter the name of the file that contains the vector b (in full detail):
>>> b.txt
SUCCESS FAR
First array:
Number of lines: 4
5.1000
5.8200
0.9700
4.9400
SUCCESS PIVOT
SUCCESS ROWSA
SUCCESS PIVOT
SUCCESS ROWSA
SUCCESS PIVOT
SUCCESS ROWSA
SUCCESS PIVOT
SUCCESS ROWSA
SUCCESS ELIM
0.7933
-1.6887
-0.0608
1.5238
Enoizat, thank you for your efforts. I will study on it to understand and write the code again with what I learn from you. Thank you again :). By the way the matrise that I work with are assumed to be square matrices and the vector b is assumed to have the number of rows that is equal to number of rows of matrix A. Thank you so much.
I will study on it

No, please, don’t :-(
My addition is simply a bugged and pathetic surrogate of std::vectors, just in case you were one of those who can’t or don’t want use them. Do study std::vectors, instead.

the matrise that I work with are assumed to be square matrices and the vector b is assumed to have the number of rows that is equal to number of rows of matrix A

Ah, ok! I should have noticed that. So, if you know the rows number, you know all the dimensions. You’re right. I’m simply not good at math.

You welcome and happy coding!
Topic archived. No new replies allowed.