Searching a File for Prime Numbers

I've been working on a project to search a file for prime numbers as well as the sum and average of them. The user enters the name of the file that they want to search. If the file contains 7 7 7 8 10 12 2 8, the program should only see 7 7 7, produce a sum of 21, and a average of 7. This is what I have so far:

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
//This program searches a txt file for prime numbers, find the sum and average.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main( )
{
    ifstream inputFile; //Allows the user to open an existing file and read it.
    string filename;    //Name of the file the program will search.
    int num;            //Whole numbers the file will contain.
    int x;              //Number used to determine the factor.
    int factor = 0;     //Number used to determine the prime.
    int count = 0;      //The amount of whole numbers.
    float sum;          //The sum of whole numbers.
    float avg;          //The average of whole numbers.

    //Displays the welcome message.
    cout << "Welcome to the Happy File Data Reader!\n";

    //Prompts user to enter filename.
    cout << "Please enter the name of the input file: ";
    cin >> filename;

    //Opens the file that is specified by the user.
    inputFile.open(filename.c_str());

    //Using an if statement to determine that the file opens.
    if(inputFile)
    {
        //Using a while loop to find the sum, average, and prime numbers.
        while(inputFile >> num)
        {
            //Using a for loop to determine if the number is prime.
            for(x=2; x<=num; x++)
            
                if(num % x == 0)
                {
                    factor++;
                }
                if(factor == 1)
                {
                    sum += num;
                    count++;
                }
            
        }

        //Finding the average of the prime numbers.
        avg = sum/count;

        //Display the imformation to the user.
        cout << "The average of the primes in " << filename << " ";
        cout << "is " << avg << " and their sum is " << sum << ".\n";
    }
    else
    {
        //Display an error message if the file is not found.
        cout << "The file "<< filename << " does not exist!\n";
    }

    //Closes the file.
    inputFile.close();

return 0;
}


The output after I run the program it will output an average of 7 and a sum of 7. I not sure why the sum is not displaying 21. I've spent many hours just trying to figure this part of the program out. I don't have any friends who are knowledgeable with C++ and I've read just about everything that I could that is related to what I'm trying to do. Can someone help me? Thanks
Last edited on
well here's your clue.. this is what I get when I compile this (visual studio 2010):

warning C4700: uninitialized local variable 'sum' used


edit 2:

This:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
		while(inputFile >> num)
		{
			//Using a for loop to determine if the number is prime.
			for(x=2; x<=num; x++)

				if(num % x == 0)
				{
					factor++;
				}
				if(factor == 1)
				{
					sum += num;
					count++;
				}

		}


You have no surrounding braces around your for loop. Also, is this the correct algo for working out prime numbers?

3. This:
 
avg = sum/count;

integer division issue.
Last edited on
I don't have Visual Studio 2010. After I initialized [ sum = 0; ] the output is - avg 7 and sum 42. Do you have the same output?
no, because sum is unitialized the first time through and is therefore garbage.

but you realise that for loop is messed up due to the missing braces yes?
Last edited on
Did you correct problems 2 and 3?
2: The braces didn't copy over for some reason but they're there.

3: The avg output is correct some how. Is there a better way to divide the sum by the amount of prime numbers to get the avg?
Last edited on
I meant this issue:
is this the correct algo for working out prime numbers?


3: Use double or float rather than int for calculations like this.
Yes I tried changing each variable to float or double. factor, count, sum, and avg can be float or double but num and x can't. I get an error because if(num % x == 0). I guess % Modulus will only allow integers.
1
2
3
4
5
6
7
 
int prime = 7; 
int prime2 = 13; 
double x, y, avg; 
x = prime; 
y = prime2; 
avg = (x + y) / 2; 
I can't hardcode the numbers (though I wish I could) because they are random. I'm just practicing with 7 7 7 8 10 12 2 8 within a txt file. I already know that output should be:

"The average of the primes in file.txt is 7 and their sum is 21."

I just don't know what code I'm missing or typing wrong.
2: The braces didn't copy over for some reason but they're there.

The braces should not be there. What should've been corrected was the indentation that lead others to believe the second if block was part of the loop. It wasn't, and shouldn't have been. In addition, you need to reset factor each time through the while loop. Declaring it closer to where you use it might make that more obvious:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ...

    //Using an if statement to determine that the file opens.
    if (inputFile)
    {
        //Using a while loop to find the sum, average, and prime numbers.
        while (inputFile >> num)
        {
            int factor = 0;

            //Using a for loop to determine if the number is prime.
            for (x = 2; x <= num; x++)
                if (num % x == 0)
                    factor++;

            if (factor == 1)
            {
                sum += num;
                count++;
            }
        }

    // ... 

That seems to give me an average of 5 and a sum of 23. Did it compile correctly for you? I'm using this website to test it more quickly.

http://www.compileonline.com/compile_cpp_online.php

I have the numbers "7 7 7 8 10 12 2 8" typed in the (input.txt) tab at the top of the page and I have "input.txt" typed in (STDIN Input) at the bottom right side of the page if anyone wants to try this site out.
Last edited on
Topic archived. No new replies allowed.