My code compiles but will not create output file:

I am using Visual Studio 2015.
I check the directory after compiling the code and no txt file pops up:

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
#include <iostream>
#include <fstream>
using  namespace std;

bool isPrime(int);

int main()
{
	fstream outfile;
	outfile.open("primesBefore100.txt");

	outfile << "The prime numbers from 1 through 100." << endl;
	for (int num = 1; num <= 100; num++)
	{

		if (isPrime(num))
			outfile << num << endl;
	}
	outfile.close();
	cin.get();
	return 0;
}

bool isPrime(int integer)
{

	if (integer == 1)
		return false;

	for (int i = 2; i <= integer / 2; i++)
	{
		if (integer%i == 0)
			return false;
	}
	return true;
}
You say you checked "the" directory. Which directory? Look around. Maybe it is not where you think.

And you should probably use ofstream for an output file:

1
2
3
    ofstream out("primesBefore100.txt");
    ...
    // and you don't need to explicitly close the file; the destructor will close it 

Also, in isPrime you don't need to check divisors up to half the input, but only up to and including the square root of the input.

1
2
3
4
5
6
7
8
9
bool isPrime(int n)
{
    if (i <= 2) return i == 2;
    if (i % 2 == 0) return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

Last edited on
Thank you for that. Turns out all i had to do was change to ofstream
Topic archived. No new replies allowed.