2D Array and File Handling [C++]

时间:2021-01-09 21:37:36

Background:

背景:

I'm attempting to read through a 2d array and find values that coincide with row numbers and column numbers.

我正在尝试读取2d数组并找到与行号和列号一致的值。

Question:

题:

How do I read values off a file and acquire, for example, 1 and 4 vs. 14?

如何读取文件中的值并获取,例如,1和4与14?

Here's what I have so far...

这是我到目前为止所拥有的......

All constructive criticism is welcome.

所有建设性的批评都是受欢迎的。

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] << ' ';
    }
}

1 个解决方案

#1


1  

You are writing rows in columns as you wrote "arrayOfNum[j][i]", but I'm writing the code for correct direction. You can change the condition in following code but it's working perfect if you write "arrayOfNum[i][j]" while outputting in 'array.txt'

当您编写“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;
}

And yes it will work for only 2 digit numbers, if you want for N digit numbers then I can do it for you too! :)

是的它只适用于2位数字,如果你想要N位数字,那么我也可以为你做! :)

#1


1  

You are writing rows in columns as you wrote "arrayOfNum[j][i]", but I'm writing the code for correct direction. You can change the condition in following code but it's working perfect if you write "arrayOfNum[i][j]" while outputting in 'array.txt'

当您编写“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;
}

And yes it will work for only 2 digit numbers, if you want for N digit numbers then I can do it for you too! :)

是的它只适用于2位数字,如果你想要N位数字,那么我也可以为你做! :)