@easybudda
Модератор
9958 / 5881 / 993
Регистрация: 25.07.2009
Сообщений: 11,119
|
21.11.2009, 14:25
|
|

Сообщение от 357STALKER
Необходимо написать программу для записи в файл элементов матрицы с последующим их чтением в другую матрицу (исходная матрица заполняется случайными числами).
C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
| #include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
ifstream fin;
ofstream fout;
char *file_name = "matrix.txt";
size_t rows, cols, i, j;
int **matrix, **matrix2;
srand(time(NULL));
cout << "Rows in matrix: ";
cin >> rows;
cout << "Columns in matrix: ";
cin >> cols;
matrix = new int* [rows];
for ( i = 0; i < rows; i++ )
matrix[i] = new int [cols];
for ( i = 0; i < rows; i++ )
for ( j = 0; j < cols; j++ )
matrix[i][j] = rand() % 100 + 1;
fout.open(file_name);
if ( !fout.is_open() ){
cerr << "Can't open output file " << file_name << endl;
exit(1);
}
for ( i = 0; i < rows; i++ ){
for ( j = 0; j < cols; j++ ){
fout << matrix[i][j] << endl;
if ( fout.fail() ){
cerr << "Can't write to file " << file_name << endl;
exit(1);
}
}
}
fout.close();
cout << endl << "Wrote to file:" << endl;
for ( i = 0; i < rows; i++ )
for ( j = 0; j < cols; j++ )
cout << matrix[i][j] << (( j < cols - 1 ) ? '\t' : '\n');
for ( i = 0; i < rows; i++ )
delete [] matrix[i];
delete [] matrix;
matrix2 = new int* [rows];
for ( i = 0; i < rows; i++ )
matrix2[i] = new int [cols];
fin.open(file_name);
if ( !fin.is_open() ){
cerr << "Can't open input file " << file_name << endl;
exit(1);
}
for ( i = 0; i < rows; i++ ){
for ( j = 0; j < cols; j++ ){
fin >> matrix2[i][j];
if ( fin.fail() ){
cerr << "Can't read from file " << file_name << endl;
exit(1);
}
}
}
fin.close();
cout << endl << "Readen from file:" << endl;
for ( i = 0; i < rows; i++ )
for ( j = 0; j < cols; j++ )
cout << matrix2[i][j] << (( j < cols - 1 ) ? ' ' : '\n');
for ( i = 0; i < rows; i++ )
delete [] matrix2[i];
delete [] matrix2;
return 0;
} |
|
1
|