Загрузка данных


#include <iostream>
#include <fstream>
#include <clocale>

using namespace std;

const int rows = 7;
const int cols = 6;

// функция подсчета нужных элементов через указатель
int countEqual(int *arr, int n, int k)
{
    int count = 0;

    for (int i = 0; i < n; i++)
    {
        if (arr[i] == k)
        {
            count++;
        }
    }

    return count;
}

int main()
{
    setlocale(LC_ALL, "Russian");

    fstream fin("in3.txt", ios::in);
    fstream fout("out3.txt", ios::out);

    if (!fin.is_open() || !fout.is_open())
    {
        cout << "Ошибка открытия файлов in3.txt или out3.txt!" << endl;
        system("pause");
        return 1;
    }

    int Y[rows][cols];

    // читаем матрицу из файла
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            fin >> Y[i][j];
        }
    }

    // выводим матрицу в консоль
    cout << "Исходная матрица Y (7x6):" << endl;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            cout << Y[i][j] << " ";
        }
        cout << endl;
    }

    // записываем матрицу в файл
    fout << "Исходная матрица Y (7x6):" << endl;
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            fout << Y[i][j] << " ";
        }
        fout << endl;
    }

    // вводим число для поиска
    int k;
    cout << "\nВведите число k: ";
    cin >> k;

    // вызываем функцию, передавая адрес начала матрицы
    int result = countEqual(&Y[0][0], rows * cols, k);

    // вывод результата
    cout << "Количество элементов, равных " << k << ": " << result << endl;
    fout << "\nЗаданное число k: " << k << endl;
    fout << "Количество элементов, равных " << k << ": " << result << endl;

    fin.close();
    fout.close();

    system("pause");
    return 0;
}