所以我有这段代码:
的main.cpp
#include "matrix.h"
int main(int argc, char *argv[])
{
matrix m;
regularMatrix rMatrix;
rMatrix.setDetails(3, "1 2 3 4 5 6 7 8 9");
//rMatrix.displayMatrix();
//int i, j, r = 0, c = 0, a;
//cout << "Enter number of Rows and Columns: " << endl;
//cin >> r ;
system("PAUSE");
return EXIT_SUCCESS;
}
matrix.cpp
#include "matrix.h"
int rows = 3, columns = 3;
int **a;
void matrix::displayMatrix(int **arr)
{
cout << "Values Of 2D Array [Matrix] Are : ";
for (int i = 0; i < rows; i++ )
{
cout << " \n ";
for (int j = 0; j < columns; j++ )
{
cout << arr[i][j] << " ";
}
}
}
void matrix::setDetails(int dimension, string y)
{
int f = dimension;
rows = dimension;
columns = rows;
string input = y;
istringstream is(input);
int n;
a = new int *[rows];
for(int i = 0; i <rows; i++)
{
a[i] = new int[columns];
}
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < columns; j++ )
{
while ( is >> n)
{
a[i][j] = n;
//cout << a[i][j] << endl;
}
}
}
matrix::displayMatrix(a);
//cout << f << endl << g << endl;
}
matrix.h
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class matrix
{
public:
virtual void displayMatrix(int** arr);
virtual void setDetails(int dimension, string y);
//virtual void setMatrix(int m[]);
//virtual void printArray(int** i);
};
class regularMatrix : public virtual matrix
{
public:
};
它运行没有错误,但问题是,当我显示矩阵时,我得到了不同的值?我想我得到了数组的地址。我怎样才能得到它的价值?我想我通过我的阵列是正确的。
答案 0 :(得分:1)
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < columns; j++ )
{
while ( is >> n)
{
a[i][j] = n;
//cout << a[i][j] << endl;
}
}
}
这实际上是错误的。看看你在这里做了什么。
在开始时,您有i = 0 and j = 0
然后你进入了while
循环。
在此处,直到您从stringstream输入int,您将a[0][0]
分配给新值。
看见?你永远不会去[0] [1]等。只有第一个元素才有效,其余元素将保持未初始化状态,因为首次执行while
循环后
istringstream对象中没有任何字符。
所以要纠正它:
for ( i = 0; i < rows; i++ )
{
for ( j = 0; j < columns; j++ )
{
if ( is >> n )
a[i][j] = n;
}
}