简体   繁体   中英

I don't know how to get a const value for my matrix that is read in from a file

I'm so confused, I wouldn't be surprised if you were confused by my question. What I am trying to do is create a program that reads in vector/matrix dimensions/contents from a file, creates arrays, and then performs operations.

ifstream in("input.txt");
stringstream buffer;
buffer << in.rdbuf();
string test = buffer.str();

string line;
ifstream file("input.txt");
string contents;
int* conv;

while (getline(file, line)){
    *conv = atoi(line.c_str());
    //cout << conv << endl;
    size_t pos = line.find("#");
    contents = line.substr(pos + 1);
    //cout << contents << endl;
}
int row = conv[4];
int column = conv[5];
int aMatrix[row];
file.close();
cin.get();

I am obviously getting the error that states that I have to have a constant value. However, since I'm reading in from a file, I'm not sure how to get a constant before I've read the file.

The file contains lines such as 34#123456789123 that translates to a 3 x 4 matrix with contents 1234...3. Most of the code up there is how I've read the file in, separated the strings into size and contents, and converted them to ints.

The function's parameters are (for example, matrix * matrix):

int** mxm(int **A, int **B, int rowsA, int colsA, int rowsB, int colsB){
    int** value = NULL;
    for (int i = 0; i < rowsA; i++){
        for (int j = 0; i < colsA; i++){
            for (int k = 0; k < colsB; k++){
                **value += A[i][j] * B[i][k];
            }
        }
    }return value;
}

EDIT: I should mention that although I can clearly see that that matrix is 3x4, the next matrix is 4x3. When I run the program, I shouldn't have any input, the program should be able to do it just from reading the file.

If you need to make an array and you will not know the size of the array until run-time you need to use pointers. You can do that like:

int rows;
std::cout << "Rows: ";
std::cin >> rows;

int * values = new int[rows];
// when done call delete [];
delete [] values;

If you need to do 2 dimensions then you can use:

int rows, cols;
std::cout << "Rows: ";
std::cin >> rows;
std::cout << "Cols: ";
std::cin >> cols;

int ** values = new int[rows];
for (int i = 0; i < rows; i++)
    values[i] = new int[cols];
// when done call delete [] for both dimensions;
for (int i = 0; i < rows; i++)
    delete [] values[i];
delete [] values;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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