[英]Why can't I use outf in a function in C++
I want to use outf
in a function but when I try it show 'undefined' error. 我想在函数中使用outf
,但是当我尝试使用它时却显示“未定义”错误。
I use visual studio 2013 and this is my code 我使用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;}
for example i want use random number 1 in a function : 例如我想在函数中使用随机数1:
void Eradom(){
for (int i = 0; i < d; i++)
{
outf << Erand[i];
outf << ",";
}
but I got error in line 4. 但我在第4行出现错误。
outf
is a local variable in your main
function. outf
是main
函数中的局部变量。 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. 为了使其可以被其他函数访问,您可以将其定义为全局变量(通常不建议使用),也可以将其显式传递给Erandom
函数。
You define outf
inside main()
, but you try to access it inside the function Erandom()
. 您可以在main()
定义outf
,但是尝试在函数Erandom()
访问它。 That is causing this error. 这是导致此错误的原因。 You must pass it to the function Erandom()
as an argument. 您必须将其作为参数传递给函数Erandom()
。
Your outf
variable is a local variable of main and thus not visible in your Erandom
function. 您的outf
变量是main的局部变量,因此在Erandom
函数中不可见。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.