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.
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
usingnamespace 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.
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.