简体   繁体   English

将矩阵字符串数组转换为整数矩阵? C ++

[英]Convert matrix string array to integer matrix? C++

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. 我知道写一个getline的while循环(类似while(line!="") getline(cin, line); )可以使多行读取为输入。 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'; 同样,而不是使用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. 我应该使用stoi,但是对于在创建新的数字数组时也如何使用stoi感到有些困惑。 ( I know it converts the string to integers but how do I actually use it to do that? ) (我知道它将字符串转换为整数,但实际上我该如何使用它呢?)

You can make use of std::istringstream in combination with std::transform and lambda expressions: 您可以将std::istringstreamstd::transform和lambda表达式结合使用:

//...
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. lambda表达式为每个输入(每个数字加上空格) std::stoi函数。 The 2nd argument is empty, as the std::istream_iterator<> indicate automatically their end (when the input is completly consumed). 第二个参数为空,因为std::istream_iterator<>自动指示它们的结束(当完全消耗了输入时)。
This solution crashes, when the input of the lambda expresion contains characters, that aren't numbers. 当lambda表达式的输入包含非数字字符时,此解决方案崩溃。 You could extend the lambda expression to handle those cases (if neccessary). 您可以扩展lambda表达式来处理这些情况(如有必要)。
(For splitting see also Split a string in C++? ) (有关拆分,另请参见在C ++中拆分字符串?

Please add some curly brackets around the corpus of your while -loop :) 请在while -loop的语料库周围添加一些花括号:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM