背景:
我试图读取一个2d数组,找到与行号和列号一致的值。
问题:
如何从文件中读取值并获取,例如,1和4与14?
以下是我迄今为止所拥有的。。。
欢迎所有建设性的批评。
int arrayOfNum[5][5] = {
{34,21,32,41,25},
{14,42,43,14,31},
{54,45,52,42,23},
{33,15,51,31,35},
{21,52,33,13,23}};
ofstream arrayFile;
arrayFile.open("arrays.txt");
if (arrayFile.is_open()) {
cout << "File opened successfully..." << endl;
}
for (int i = 0; i <= 4; i++) {
arrayFile << endl;
for (int j = 0; j <= 4; j++) {
arrayFile << arrayOfNum[j][i] << ' ';
}
}
您在写"arrayOfNum[j][i]"时是在列中写行,但我在写正确方向的代码。您可以在下面的代码中更改条件,但如果您在"array.txt"中输出时写入"arrayOfNum[i][j]",它将非常有效
ifstream arrayFile;
arrayFile.open("arrays.txt");
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
arrayFile >> arrayOfNum[i][j];
cout<<arrayOfNum[i][j]<<" ";
if(i+1 == arrayOfNum[i][j] / 10 && j+1 == arrayOfNum[i][j] % 10)
{
cout<<"n Matched: "<<arrayOfNum[i][j]<<endl;
}
}
cout<<endl;
}
是的,它只适用于2位数,如果你想要N位数,那么我也可以为你做!:(