带数组的istream / ostream参数

时间:2015-05-07 15:25:55

标签: c++ arrays istream

好的,所以我有这个代码,我在操作数组,但我知道我在这里做了一些非常错误的事情而我无法识别它。我应该使用istream和ostream参数......我认为,还有数组和int变量。这是代码和我得到的:

#include <iostream>;

#include <fstream>;

using namespace std;


//input data
void inputData(istream &, int[], int);

//print data
void printData(ostream &, const int[], int);

//copy one array to another
void copyArray(const int orig[], int dup[], int);

// copy one array to another in reverse
void revCopy(const int orig[], int rev[], int);

int main()
{
ifstream in;
ofstream out;

int x[10];
int y[10];
int z[10];

inputData( cin, x, 10);

printData(cout, x, 10);

copyArray(x, y, 10);

printData(cout, y, 10);

revCopy (y, z, 10);

printData(cout, z, 10);




return 0;
}

//input data
void inputData(istream & cin, int x[], int i)
{
cout << "Enter in 10 Values for array \"x\"" << endl;


for(i = 0; i <10; i++)
{
    cin >> x[i];
}
}

//print data
void printData(ostream & cout, const int x[], int i)
{
for (i = 0; i <10; i++)
{
    cout << x[i];
}

}

//copy one array to another
void copyArray(const int orig[], int dup[], int)
{

}


// copy one array to another in reverse
void revCopy(const int orig[], int rev[], int)
{

}

这是我到目前为止所做的,我试图在继续之前测试打印功能,我似乎无法超越这个:

Enter in 10 Values for array "x"
1
2
3
4
5
6
7
8
9
10
12345678910-858993460-858993460-858993460-858993460-858993460-858993460-85899346
0-858993460-858993460-858993460-858993460-858993460-858993460-858993460-85899346
0-858993460-858993460-858993460-858993460-858993460Press any key to continue . . .

我是c + +的新手,现在正在上课,但是这个让我感到难过,过去几天一直试图解决这个问题,而我的导师已经无法使用了。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

你宣布

int z[10];

此时z内的所有数据都未初始化,对它的任何访问都是未定义的行为。稍后你的代码会调用

revCopy (y, z, 10);

但是这个功能还没有实现;什么都没有被放入z,它仍然是未初始化的数据。所以打电话给

printData(cout, z, 10);

会导致未定义的行为,因此您会看到垃圾输出。如果您在实施其他功能之前只是进行测试,我建议您先初始化z

相关问题