I want to use outf
in a function but when I try it show 'undefined' error.
I use visual studio 2013 and this is my code
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;}
for example i want use random number 1 in a function :
void Eradom(){
for (int i = 0; i < d; i++)
{
outf << Erand[i];
outf << ",";
}
but I got error in line 4.
outf
is a local variable in your main
function. To make it accessible to other functions you could either define it as a global variable (usually not recommended), or explicitly pass it to the Erandom
function.
You define outf
inside main()
, but you try to access it inside the function Erandom()
. That is causing this error. You must pass it to the function Erandom()
as an argument.
Your outf
variable is a local variable of main and thus not visible in your Erandom
function. To pass the variable into your function, define it like
void Eradom(std::ostream &outf) {
for (int i = 0; i < d; i++) {
outf << Erand[i];
outf << ",";
}
}
And call it from main as
Eradom(outf);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.