【问题标题】:" 'X' not declared in this scope " error“ 'X' 未在此范围内声明” 错误
【发布时间】:2014-02-22 11:31:52
【问题描述】:

我对编程很陌生,我刚上大学一年级的第二个学期,所以请在技术术语上放轻松。我们被要求编写一个程序,从文件中读取 10 个整数来组成一个列表,并要求用户输入一个整数“N”。如果“N”在列表中,否则程序应显示“FOUND”和“NOT FOUND”。我在 main 中收到有关参数的错误,它表示函数调用中的“V”、“N”和“F”“未在此范围内声明”。

#include<iostream>
#include<fstream>

using namespace std;

int fRead();
int iRead();
bool search(int, int);
void display(bool);

int main() {
 fRead();
 iRead();
 search(V, N);
 display(F);
 return 0;
}

int fRead() {
 int V[10], c;
 ifstream fin;
 fin.open("lab02.in");
 for(c=0; c<10; c++)
  fin >> V[10];
 fin.close();
 return V[10];
}

int iRead() {
 int N;
 cout << "Input an integer: ";
 cin >> N;
 return N;
}

bool search(int V[10], int N) {
 bool F = false;
 if(V[10] == N)
  F = true;
 return F;
}

void display(bool F) {
 if(F == true)
  cout << "\nFOUND" << endl;
 else
  cout << "\nNOT FOUND" << endl;
}

【问题讨论】:

  • 这样做的原因是您在单独的方法中声明了 F、V 和 N,但也在 main 中使用它们。尝试在 main 中声明它们,你应该没问题。
  • 你需要在使用之前声明东西。 VFN 在声明之前用于 main
  • 您使用数组的方式也有很多问题。 V[10] 访问数组边界之外。
  • 对缩进有点概念。我会将其增加到至少三个空格。还要使用大括号,因为这是一个很好的指示符或语句块的开始及其终止。由于您是发布了一些合理代码的新手,因此您会获得 +1
  • ...忘记添加 - 请给变量更有意义的名称

标签: c++


【解决方案1】:

局部变量(在函数中声明的变量)仅对声明它们的块(由{} 分隔的东西)可见。如果您想为各种操作使用不同的函数,您需要将变量作为参数传递给相应的函数。

顺便说一句,您应该始终在使用结果之前验证您的读取操作是否成功,例如:

int N(-1);
if (!(std::cin >> N)) {
    std::cout << "ERROR: failed to read integer\n";
}

【讨论】:

    【解决方案2】:

    整数V N 和F 基本上在其他函数中描述。 要解决此问题,您应该在 main 中声明它们 程序应该如下所示

          void f_read(v[]);
            void i_read(int &);
            bool bool(int,int);
            void disp(bool);   
             void main()
                {
                    int v[10],n;
                    bool f;
                    f_read(v);
                    i_read(n);
                    f=bool(v,n);
                    disp(f);
                }
        void fRead() 
    {
        int c;
         ifstream fin;
         fin.open("lab02.in");
         for(c=0; c<10; c++)
          fin >> V[c];
         fin.close();
    
        }
    
        void iRead(int &n)
     {
    
         cout << "Input an integer: ";
         cin >> N;
    
        }
    
        bool search(int V[10], int N)
        {
         bool F = false;
    int i;
    for(i=0;i<=9;i++)
         if(V[i] == N)
         { 
          F = true;
         return F;
    }
        }
    
        void display(bool F) 
        {
         if(F == true)
          cout << "\nFOUND" << endl;
         else
          cout << "\nNOT FOUND" << endl;
        }
    

    所以基本上你需要将 n 作为引用变量传递,而数组默认作为引用传递。

    你也在寻找 v[10]=f ,这会给你另一个数组,我也更正了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2015-06-23
      • 2010-10-02
      相关资源
      最近更新 更多