c++ - 从文件中读取数组的最佳方法
问题描述
我在一个文件中写了一个数组,现在我试图从同一个文件中读取它。但是,当我打印它时,它会给出非常奇怪的数字。我想知道这些数字是从哪里来的(是地址吗?),我该如何解决。我想知道是否可以写一些东西,这样你就不必每次使用 is 时都写相同的循环(我指的是带有 i 和 j 的那个)。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <time.h>
int main () {
int n,m;
cout<<"Enter number of rows: "<<endl;
cin>>n;
cout<<"Enter number of columns: "<<endl;
cin>>m;
int** b = new int*[n];
for (int i = 0; i < n; ++i)
{ b[i] = new int[m]; }
srand(time(0));
int max=9, min=-9;
for( int i = 0; i<n; ++i) {
for( int j = 0; j<m; ++j) {
b[i][j] = (rand()%
(max-min+1))+min;}
}
cout << " Array :" << endl;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cout << setw(5) << b[i][j];
}
cout<< endl;
}
ofstream array ("Array_2D.txt", ios::out);
for(int i=0; i<n; i++){
for (int j=0; j<m; j++) {
array << b[i][j] ;
}
}
ifstream readarray ("Array_2D.txt" , ios :: in);
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{ p[i] = new int[m]; }
for (int i=0; i<n; ++i)
for (int j=0; j<m; ++j)
readarray >> p[i][j];
cout << " Array C: " << endl;
for(int i=0; i<n; ++i ) { // Вывод матрицы на экран
for(int j=0; j<m; ++j)
cout << p[i][j] << " ";
cout << endl;
}
解决方案
试试这个:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
int n, m;
cout << "Enter number of rows: " << endl;
cin >> n;
cout << "Enter number of columns: " << endl;
cin >> m;
int** b = new int* [n];
for (int i = 0; i < n; ++i)
{
b[i] = new int[m];
}
srand(time(0));
int max = 9, min = -9;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
b[i][j] = (rand() %
(max - min + 1)) + min;
}
}
cout << " Array :" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << setw(5) << b[i][j];
}
cout << endl;
}
ofstream array("Array_2D.txt", ios::out);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
array << b[i][j] << " ";
}
array << endl;
}
ifstream readarray("Array_2D.txt", ios::in);
int** p = new int* [n];
for (int i = 0; i < n; ++i)
{
p[i] = new int[m];
}
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
readarray >> p[i][j];
cout << " Array C: " << endl;
for (int i = 0; i < n; ++i) { // Вывод матрицы на экран
for (int j = 0; j < m; ++j)
cout << p[i][j] << " ";
cout << endl;
}
}
最初,您没有在数字之间写入空格,因此它只读取一个奇怪的数字,而其他数字未初始化。
示例 I/O:
Enter number of rows:
5
Enter number of columns:
5
Array :
9 7 3 7 7
-6 -2 -1 5 -4
5 -5 8 -4 -7
-1 7 -9 -5 3
-5 -2 1 0 -8
Array C:
9 7 3 7 7
-6 -2 -1 5 -4
5 -5 8 -4 -7
-1 7 -9 -5 3
-5 -2 1 0 -8
推荐阅读
- javascript - 即使在组件卸载后也无法阻止 window.onScroll 触发
- angular - 如何将 JSON 从 Angular 7 传递到 Datatable 组件
- python - DASH - 在函数外获取数据帧(df)
- vb.net - Telerik ajax ASP Visual Basic
- jsp - 如何访问 forEach 循环中的动态列表项?
- python - 大写()方法如何在 python/django 中工作?
- javascript - Cocos2d (JS) - 设置 OnLoad() 并具有属性 isPlaying: true 的动画根本没有真正播放
- jestjs - 玩笑 test.each 在名称中具有对象属性
- javascript - 组件中的Angular 7滚动事件重新渲染滚动上的所有组件
- python - 最后 x 行的 Pandas 平均值