2015-05-02 173 views
1

我想在函数中使用outf,但是当我尝试显示'undefined'错误时。为什么我不能在函数中使用outf在C++中

我使用Visual Studio 2013,这是我的代码

int main(){ 

int costumer; 
int d; 
cout <<"Enter Number : "; 
cin >> costumer; 
d = costumer; 
int *Erand = new int[d]; //Random Number 1 
int *Srand = new int[d]; //Random Number 2 
int *SumArrays = new int[d]; // sum Array 
ofstream outf("Sample.dat"); 

//------------------------- Make Random Numbers 

srand(time(0)); 
for (int i = 0; i< d; i++) 
{ 
    Erand[i] = 1 + rand() % 99; 
} 
for (int i = 0; i< d; i++) 
{ 
    Srand[i] = 1 + rand() % 999; 
} 
//---------------------------- Out Put 
outf << "Random Number 1 " << endl; 
for (int i = 0; i < d; i++) // i want it in a function 
{ 
    outf << Erand[i]; 
    outf << ","; 
} 
outf << endl; 

outf << "Random Number 2 " << endl; 
for (int i = 0; i < d; i++)// i want it in a function 
{ 
    outf << Srand[i]; 
    outf << ","; 
} 
outf << endl; 
//--------------------------------calculator ------------------------- 
for (int i = 0; i < d; i++) 
{ 
    SumArrays[i] = Erand[i] + Srand[i]; 
} 
outf << "Sum Of Array is : "; 
outf << endl; 
for (int i = 0; i < d; i++) 
{ 
    outf << SumArrays[i]; 
    outf << ","; 
} 
outf << endl; 
delete[] Erand; 
delete[] Srand; 
delete[] SumArrays;} 

比如我想使用的功能随机数1:

void Eradom(){ 
for (int i = 0; i < d; i++) 
{ 
    outf << Erand[i]; 
    outf << ","; 
} 

,但我行有错误4.

+4

因此,这是第4行? –

回答

0

您在main()的内部定义了outf,但您尝试在函数Erandom()内部访问它。这是造成这个错误。您必须将它作为参数传递给函数Erandom()

1

outfmain函数中的局部变量。为了使其可以被其他函数访问,您可以将其定义为全局变量(通常不推荐),或者将其明确地传递给Erandom函数。

0

您的outf变量是main的局部变量,因此在您的Erandom函数中不可见。为了变量传递到你的函数,定义它像

void Eradom(std::ostream &outf) { 
    for (int i = 0; i < d; i++) { 
    outf << Erand[i]; 
    outf << ","; 
    } 
} 

而且从主称其为

Eradom(outf); 
相关问题