0

I'm having trouble trying to have the user input a string matrix of numbers and trying to convert them to integers so I can perform numerical operations on matrices. My code is below.

    int matrix1[10][10];

    string first_matrix;

    cout << "Enter first matrix:\n";
    while (first_matrix != " ")
        getline(cin, first_matrix);
        for(int i = 0; i < strlen(first_matrix); i++)
            if(first_matrix[i] == "")
                break;
            else(first_matrix[i] == " "){
                n = n + 2;
                if (first_matrix[i] == "\n"){
                    m++;
                }
                first_matrix[i] = matrix1[i] - '0';
            }

    return 0;

I know writing a while loop for getline (something like while(line!="") getline(cin, line);) makes it so that multiple lines can be read as input. But my question is how would I extract these lines of strings and put them into a new array with their integer forms? Also, rather than using first_matrix[i] = matrix1[i] - '0'; I'm supposed to use stoi, but I'm a bit confused on how to use stoi also while creating a new array of numbers. ( I know it converts the string to integers but how do I actually use it to do that? )

digggzz
  • 83
  • 1
  • 6

1 Answers1

0

You can make use of std::istringstream in combination with std::transform and lambda expressions:

//...
getline( cin, first_matrix );
std::istringstream inputStream( first_matrix );
std::transform(
    std::istream_iterator<std::string>(inputStream),
    std::istream_iterator<std::string>(),
    matrix1[i],
    [] (std::string in) -> int { return std::stoi(in); }
);

The lambda expression calls for each input (each number accompanied by white space(s)) the std::stoi function. The 2nd argument is empty, as the std::istream_iterator<> indicate automatically their end (when the input is completly consumed).
This solution crashes, when the input of the lambda expresion contains characters, that aren't numbers. You could extend the lambda expression to handle those cases (if neccessary).
(For splitting see also Split a string in C++?)

Please add some curly brackets around the corpus of your while-loop :)

Community
  • 1
  • 1
camelCase
  • 187
  • 1
  • 12