-9

I'm a beginner in C++ programming I have a text file which has 1 million prime numbers separated by spaces. I want to put them in an int array primes[]. Following is the code that I have written:

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;
}

When I build and run, it gives the following error:

"Error: 'primes' was not declared in this scope"

What is the solution to this?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
AmanArora
  • 9
  • 2

3 Answers3

5

I highly recommend to use a vector instead of an array on the heap to prevent resource leaks:

std::vector<int> primes;
int p;
while (infile >> p)
{
    primes.push_back(p);
}
fredoverflow
  • 237,063
  • 85
  • 359
  • 638
5

C++ is beautiful has nice stuff in its library that allows you to do this in a high-level, concise, declarative manner:

std::vector<int> primes(std::istream_iterator<int>{infile},
                        std::istream_iterator<int>{});
rightfold
  • 30,950
  • 10
  • 83
  • 106
1

What is the solution to this?

Declare primes. The identifier must be declared first in order to assign something to it.

For example:

int *primes = new int[1000001];
Karadur
  • 1,186
  • 8
  • 15