Search code examples
c++variablesfstream

Assign last number of a text file to a variable C++


I am doing a program that outputs a list of prime numbers with fstream.

I have this so far:

int export_list (int lim = 50)
{
    int x;
    last_in_txt = ????????????; // assigns last number on txt

    ofstream file ("Primes.txt" , ios::app);

    if (file.is_open()) // if it opens correctly
    {
        for (x = last_in_txt ; x < lim ; x++)
        {
            if (check_prime (x)) // returns 1 when x is prime, returns 0 when not
            {
                file<< x << " ";
            }
        }
        cout << "Done!" << endl << pressenter;
        cin.get();
    }
    else
    {
        cout << "Unable to open file" << endl << pressenter;
        cin.get();
    }
    return(0);
}

So, as you can see, this should append a list of prime numbers to Primes.txt, starting with the prime 1234547.

Primes.txt looks like this:

2 3 5 7 11 13 17 19 23 29 31 37 (...) 1234543 1234547 

My question is how do I assign 1234547 (which is the last number of the txt) to the variable last_in_txt?

Other (not so important) question: Should I save the numbers the way I'm currently doing, or should I store each number in a separate line?


Solution

  • One simple way: keep reading and assign until the whole file is read.

    For example,

    int last_in_txt = 0;
    {
        ifstream infile("Prime.txt");
        int k;
        while(infile >> k) {
            last_in_txt = k;
        }
    }
    // Now last_in_txt is assigned properly, and Prime.txt is closed
    

    This works well no matter the numbers in Prime.txt are separated by space characters (' ') or by newline characters ('\n').