Problems using seekg

Okay, so I have an assignment that involves writing all prime numbers between 0 and one million to a text file and then to have the user input a certain number between that range. Using the inputted number I am to use seekg() to find the inputted number and then print out the closest next prime. So far I'm entirely unsure how to use seekg() to print out the next prime.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

//Prototype
bool isPrime(int);

int main()
{ 
 ofstream outFile;
   outFile.open("Prime.txt");
   
   //Error checking
    if (!outFile)
    {
        cout << "***ERROR opening file. Check and run again.\n";
        return 0;
    }
    
    //Declarations
    int primeNum = 0;
    int count = 0;
    int num = 0;
    char ch;
    
    
    
    //Find all primes and write them to file
    for(int i = 0; i < 100; i++)
    {
        if (isPrime(i))
        {
             count++;
             outFile << i << "\n";
             primeNum = i;
        }
        
    }
    
    //Open ifstream for input 
   ifstream ifFile;
   ifFile.open("Prime.txt");
   
    //Output
    cout << "There are a total of " << count << " prime numbers under one million.\n";
    cout << "\nThe largest prime number is " << primeNum;

    //Input
    
    cout << "\nPlease input a integer between 0 and 1,000,000: ";
    cin >> num;
    
    //Input validation
    if(num < 0 || num > 1000000)
    {
        cout << "\nError! Please only enter an integer between 0 and 1,000,000! Re-enter now: ";
        cin >> num;
    } 
    
    
    // ifFile.seekg(ios::beg);
    // cout << ifFile.tellg();
    
     ifFile.seekg(num, ios:: beg);
        
    cout << "\nThe closest prime after the inputted number is "<< ifFile.tellg()  << endl; 
    //Close File
    ifFile.close();
    outFile.close();
    return 0;
}
if you write the file in binary mode, this would be a lot easier.
otherwise you are going to maybe want to cheat and write some spaces after the smaller numbers so every line is the same size so you can calculate where to move to.
outFile.open("Prime.txt");
///
ifFile.open("Prime.txt");

Opening the file for input, while it's still open for output isn't likely to work.
It'll work just fine. On windows, however, there is a design flaw in stream handling rendering seekg() and tellg() useless: newline translation.

Open your file in binary. If you use getline() at any point, you'll need to extract and discard the '\n' explicitly before doing anything else with the string; otherwise you are unlikely to have any other problems.

Hope this helps.
Topic archived. No new replies allowed.