2015-05-02 138 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); 
相關問題