![](/img/trans.png)
[英]Want c++ to get these variables into an array from a text file.But I don't know how to specify locations in a text file
[英]I don't know how to get a const value for my matrix that is read in from a file
我很困惑,如果你對我的問題感到困惑,我不會感到驚訝。 我要做的是創建一個程序,從文件中讀取向量/矩陣維度/內容,創建數組,然后執行操作。
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();
我顯然得到的錯誤表明我必須有一個恆定的值。 但是,因為我正在讀取文件,所以我不確定在讀取文件之前如何獲得常量。
該文件包含34#123456789123等行,轉換為內容為1234 ... 3的3 x 4矩陣。 大多數代碼都是我如何讀取文件,將字符串分成大小和內容,並將它們轉換為整數。
函數的參數是(例如,矩陣*矩陣):
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;
}
編輯:我應該提一下,雖然我可以清楚地看到該矩陣是3x4,但下一個矩陣是4x3。 當我運行程序時,我不應該有任何輸入,程序應該只能通過讀取文件來完成。
如果你需要創建一個數組,並且在運行時你不知道數組的大小,你需要使用指針。 你可以這樣做:
int rows;
std::cout << "Rows: ";
std::cin >> rows;
int * values = new int[rows];
// when done call delete [];
delete [] values;
如果您需要做2個維度,那么您可以使用:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.