我需要一些帮助。我正在尝试从文件中读取。该文件包含以下内容:
1x+1y+1z=5
2x+3y+5z=8
4x+0y+5z=2
我想将其存储到一个二维数组中。行为 3,列始终为 4。我只想存储整数值,在本例中为 1 1 1 5 2 3 5 8 4 0 5 2。如何将这些值存储到数组中?这是我尝试做的,但没有用。感谢您的帮助。
int main(){
fstream file;
file.open("matrix.txt", ios::in);
int arr[3][4];
// copy integers into array and display
for (int i = 0; i < 3; i++){
for(int j= 0; j < 4; j++){
file >> arr[i][j];
cout << arr[i][j];
}
}
}
最佳答案
您需要先从每个方程中提取数字,然后将它们存储在数组中。我将向您展示如何提取这些数字,我想剩下的就很简单了。
#include <iostream>
#include <string>
using namespace std;
void getNumbers(string str, int&x, int&y, int& z)
{
string X, Y, Z;
size_t idx = str.find("x");
size_t idy = str.find("y");
size_t idz = str.find("z");
X = str.substr(0, idx);
Y = str.substr(idx+1, idy-(idx+1));
Z = str.substr(idy+1, idz-(idy+1));
x = stoi(X);
y = stoi(Y);
z = stoi(Z);
}
int main()
{
string line("2x+82y-12z=5");
int x(0), y(0), z(0);
getNumbers(line,x,y,z);
cout << line << endl;
cout << x << " " << y << " " << z << endl;
return 0;
}
结果是
2x+82y-12z=5
2 82 -12
关于c++ - 将数据存储到多维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46518884/