file storage

can someone confirm I did my assignment correctly and if need be let me know what i can improve on

update on checking file only last number appears

the goal is to find prime numbers 0-100
and store result in a user determined file area


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
#include <iostream>
#include <fstream>
#include <string>
using namespace 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;
}
Last edited on
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

#include <iostream>
#include <fstream>
#include <string>
using namespace 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

bool isPrime(int n) {
    for (int i = 2; i * i <= n; ++i)
        if (n % i == 0)
            return false;
    return true;
}

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

Last edited on
thanks so much now i realize that I essentially was writing and re writing over the same spot. @dutch
Topic archived. No new replies allowed.