【问题标题】:not declared in this scope (arrays in C++) [closed]未在此范围内声明(C++ 中的数组)[关闭]
【发布时间】:2014-07-26 07:52:16
【问题描述】:

我是 C++ 编程的初学者 我有一个文本文件,其中有 100 万个以空格分隔的素数。我想把它们放在一个 int 数组 primes[] 中。以下是我写的代码:

int main()
{
    ifstream infile;
    infile.open("C:/Users/DELL/Desktop/primes1.txt");

    //check for error
    if(infile.fail()){cerr<<"Error Opening File"<<endl;
    exit(1);}
    int i=0;
    primes = new int[1000001];
    while(i != infile.eof()){
        infile>>primes[i];
        i++;
    }

    cout<<  primes[4]  <<endl;

    return 0;
}

当我构建并运行时,它给出了以下错误:

“错误:'primes' 未在此范围内声明”

解决办法是什么?

【问题讨论】:

  • 你的素数声明在哪里?
  • 你的意思是写int* primes = new int[1000001];
  • primes = new int[1000001]; --> int *primes = new int[1000001];
  • 还是在栈上而不是在堆上分配?
  • while(i != infile.eof()) 看起来很不对劲。

标签: c++ arrays file text error-handling


【解决方案1】:

C++ is beautiful 在它的库中有一些不错的东西,可以让你以一种高级的、简洁的、声明性的方式做到这一点:

std::vector<int> primes(std::istream_iterator<int>{infile},
                        std::istream_iterator<int>{});

【讨论】:

  • +1 我也希望看到 C++98 解决方案!
  • @FredOverflow 用大括号代替括号,并将 std::vector&lt;int&gt; 的构造函数的任一参数用括号括起来。
  • 或将 std::copy 与 back_inserter 一起使用。
  • 顺便说一下,你可以用 {} 替换第二个参数,这样std::vector&lt;int&gt; primes(std::istream_iterator&lt;int&gt;{infile},{}); 就可以了。
【解决方案2】:

我强烈建议在堆上使用向量而不是数组来防止资源泄漏:

std::vector<int> primes;
int p;
while (infile >> p)
{
    primes.push_back(p);
}

【讨论】:

    【解决方案3】:

    解决办法是什么?

    声明primes。必须先声明标识符才能为其赋值。

    例如:

    int *primes = new int[1000001];
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 2013-10-25
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多