#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int isPrimeNumber(int);
int main()
{
ofstream f;
string filename;
bool isPrime;
cout << "What is the file name you want to store this in? " << endl << "Filename: ";
getline(cin, filename);
for (int n = 2; n < 100; n++) {
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if (isPrime == true) {
f.open(filename.c_str());
f << n << " ";
f.close();
}
}
return 0;
}
// Function that checks whether n is prime or not
int isPrimeNumber(int n) {
bool isPrime = true;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int isPrimeNumber(int);
int main()
{
ofstream f;
string filename;
bool isPrime;
cout << "What is the file name you want to store this in? " << endl << "Filename: ";
getline(cin, filename);
f.open(filename.c_str());
for (int n = 2; n < 100; n++) {
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if (isPrime == true) {
f << n << " ";
}
}
f.close();
return 0;
}
// Function that checks whether n is prime or not
int isPrimeNumber(int n) {
bool isPrime = true;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
You should only test up to the square root of n (for primes up to 100 you only need to test 2, 3, 5, and 7).
And you should open the file before the loop, store the numbers during the loop, and close it after.
You can open it with the constructor, and it will be automatically closed at the end of the function.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
bool isPrime(int n) {
for (int i = 2; i * i <= n; ++i)
if (n % i == 0)
returnfalse;
returntrue;
}
int main() {
cout << "Enter the filename to store the results: ";
string filename;
getline(cin, filename);
ofstream f(filename);
for (int n = 2; n < 100; ++n)
if (isPrime(n))
f << n << '\n';
}