背景:

我试图读取2d数组并查找与行号和列号一致的值。

题:

如何从文件中读取值并获取例如1和4 vs. 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位数字,那么我也可以为您完成! :)

09-10 00:05