Hello. I start programming in C ++, I have a program that reads matrices from a txt file.

#include <fstream> #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "RUSSIAN"); //Создаем файловый поток и связываем его с файлом ifstream in("C:\\Users\\1\\Desktop\\matriza.txt"); if (in.is_open()) { //Если открытие файла прошло успешно //Вначале посчитаем сколько чисел в файле int count = 0;// число чисел в файле int temp;//Временная переменная while (!in.eof())// пробегаем пока не встретим конец файла eof { in >> temp;//в пустоту считываем из файла числа count++;// увеличиваем счетчик числа чисел } //Число чисел посчитано, теперь нам нужно понять сколько //чисел в одной строке //Для этого посчитаем число пробелов до знака перевода на новую строку //Вначале переведем каретку в потоке в начало файла in.seekg(0, ios::beg); in.clear(); //Число пробелов в первой строчке вначале равно 0 int count_space = 0; char symbol; while (!in.eof())//на всякий случай цикл ограничиваем концом файла { //теперь нам нужно считывать не числа, а посимвольно считывать данные in.get(symbol);//считали текущий символ if (symbol == ' ') count_space++;//Если это пробел, то число пробелов увеличиваем if (symbol == '\n') break;//Если дошли до конца строки, то выходим из цикла } cout << count_space; //Опять переходим в поток в начало файла in.seekg(0, ios::beg); in.clear(); //Теперь мы знаем сколько чисел в файле и сколько пробелов в первой строке. //Теперь можем считать матрицу. int n = count / (count_space + 1);//число строк int m = count_space + 1;//число столбцов на единицу больше числа пробелов double **x; x = new double*[n]; for (int i = 0; i < n; i++) x[i] = new double[m]; //Считаем матрицу из файла for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) in >> x[i][j]; //Выведем матрицу for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) cout << x[i][j] << "\t"; cout << "\n"; } for (int i = 0; i < n; i++) delete[] x[i]; delete[] x; in.close();//под конец закроем файла } else { //Если открытие файла прошло не успешно cout << "Файл не найден."; } system("pause"); return 0; } 

The task is as follows: read two matrices from two text files, multiply them and output the result to the third file. Also consider all exceptions. How matrices are multiplied in C ++ - I figured it out. But I need the names of the three files to be specified as command line arguments. Read from the files you need two matrices, and not using duplications of the above code. How can I avoid duplicating code if I need to read two matrices and how to organize the names of the three files to be command line arguments? Thank!

  • Are you sure your code works? - Shadasviar 4:34 pm
  • Yes it works. Launched. - a novel Alexander
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

How can I avoid duplicate code if I need to read two matrices

 static double **get_matrix_from_file( const char *filename ) { /* * возвращает NULL (nullptr) в случае ошибки, * иначе - содданную матрицу */ } 

How to organize, that names of three files were command line arguments?

 int main( int argv, char **argv ) 

In more detail - here .

  • Since we are writing in C ++, rather than C, then rather static Matrix* Matrix::init_from_file(const char* filename) { /* выбрасывает исключение в случае ошибки */ } - VladD

To begin with, for convenience, we define the structure:

 struct Matrix{ double** matr; int x; int y; }; 

Next, the code for reading the matrix will be put into a separate function that takes the name of the file and returns the matrix:

  Matrix read_matrix(char* filename){ ifstream in(filename); if (in.is_open()) { int count = 0; int temp; while (!in.eof()) { in >> temp; count++; } /*Тут нужно было поменять две команды местами, сначала очищаем флаги потока, а потом переводим каретку на начало, а не наобороты*/ in.clear(); in.seekg(0, ios::beg); int count_space = 0; char symbol; while (!in.eof()) { in.get(symbol);//считали текущий символ if (symbol == ' ') count_space++; if (symbol == '\n') break; } cout << count_space; in.seekg(0, ios::beg); in.clear(); int n = count / (count_space + 1); int m = count_space + 1; double **x; x = new double*[n]; for (int i = 0; i < n; i++) x[i] = new double[m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) in >> x[i][j]; in.close(); return (Matrix){x, n, m}; } else { cout << "Файл не найден."; return (Matrix){0,0,0}; } } 

And then we just work with this function, reading the arguments of the program in a standard way, like this:

 int main(int argc, char*argv[]) { setlocale(LC_ALL, "RUSSIAN"); if(argc < 4) exit(0); Matrix m[3]; for(int i(1); i < 4; ++i){ m[i-1] = read_matrix(argv[i]); show_matrix(m[i-1]); } for(int j(0); j < 3; ++j){ for (int i = 0; i < m[j].x; i++) delete[] m[j].matr[i]; delete[] m[j].matr; } return 0; } 
  • Thank you very much for the algorithm! But I would like to clarify a couple of points: in the rows return (Matrix) {0, 0, 0}; and return (Matrix) {x, n, m}; underlined in red brace and writes "required expression" ..? And the block where the arguments are read- show_matrix is ​​not defined. Where is it determined? - a novel Alexander
  • You need to write Show_matrix yourself, and why it emphasizes red and writes something: probably such an idea, this construction of an anonymous structure was still in C, but it can be replaced with Matrix m = {nullptr, 0,0} - Shadasviar
  • Even then, the question is: how do I correctly write the condition: if the number of columns (n) of the first matrix is ​​equal to the number of rows (m) of the second matrix, multiply. Otherwise, an error. ? - a novel Alexander
  • In the ordinary condition if - Shadasviar
  • It's clear. How can I refer to variables: the number of columns of the first matrix and the number of rows of the second matrix? How do I call these values? - a novel Alexandr