It is required to develop a program to do Matrix operations. The program use a defined string format to represent the matrix in the user input and output sections. For the following matrix: examplee : the user input the string representation of the Matrix : ex:[10 2.13 3;-5 0 4;16.5 1 8] In the program, the user enters a matrix in the defined string format then asked to enter an operator
so i can't convert this string to an array to make operations as sum or multiply
using namespace std;
int main() {
int i, j, n;
string s1;
float m1[100][100];
getline(cin, s1);
for (int i = 0; i < 100; i++) {
for (n = 0; n < s1.length(); n++) {
if (isspace(s1.at(i)));
}
}
}
One algorithm to parse / read matrices like
could be:
Indices
col
androw
are initialized with0
.A loop which skips characters of the input string until a
'['
is found.A loop which reads the input string character for character with the following handling
'0'
,'1'
, ... ,'9'
,'+'
,'-'
,'.'
,'e'
,'E'
: collect character (It's part of a number.)' '
: If there are collected characters, convert them to afloat
(e.g. usingstrtod()
), store the result in matrix element (row
,col
), and incrementcol
afterwards.';'
: If there are collected characters, convert them to afloat
(e.g. usingstrtod()
), store the result in matrix element (row
,col
).Increment
row
and resetcol
to0
.']'
: If there are collected characters, convert them to afloat
(e.g. usingstrtod()
), store the result in matrix element (row
,col
).Reading of this matrix is done.
Everything else is a syntax error.
Notes:
strtod()
has a second argument which returns a pointer to first not-accepted character. This should be checked whether it points to end of collected characters. (Otherwise, the algorithm may accept e.g."1.23+1"
as1.23
without noticing the syntax error at+
.The above algorithm could/should also return the number of rows and columns collected.
Whenever a new row is started, the columns should/could be checked before whether the previous row was ful. (This excludes the first row which actually defines how many columns are there.)
The maximum possible number of rows and columns should be considered as well as a two-dim. C array is used.