Convert string into array of matrix

2019-06-14 20:54发布

问题:

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)));
        } 
    }
}

回答1:

One algorithm to parse / read matrices like

[10 2.13 3;-5 0 4;16.5 1 8]

could be:

  1. Indices col and row are initialized with 0.

  2. A loop which skips characters of the input string until a '[' is found.

  3. 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 a float (e.g. using strtod()), store the result in matrix element (row, col), and increment col afterwards.
    • ';': If there are collected characters, convert them to a float (e.g. using strtod()), store the result in matrix element (row, col).
      Increment row and reset col to 0.
    • ']': If there are collected characters, convert them to a float (e.g. using strtod()), 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" as 1.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.