Reading and counting from a file

Hello,

I created a function last week that marks true if a number is prime. Now I am trying to read from a .txt file and count the prime numbers within it.

the .txt files has numbers ranging from 2 to 10,000.

It seems I have created an infinite loop and im not really sure why. I tried to keep the function I created the same but I think im just getting caught up somewhere in the file input part.

anyways figured I would see if you guys had some suggestions.

thanks,

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
  #include <iostream>
#include <fstream>
#include <string>
#include <cmath>


bool isprime (int);

using namespace std;

int main() {

cout << "Welcome to File input" << endl;
cout << endl;

string fileName;
cout << "Please enter file name: ";
getline(cin,fileName);

ifstream fin;
fin.open(fileName);

if(fin.is_open()){
    double n;
    while (fin >> n){

            bool isPrimenumber;
                for( int n = 2; n <= 10000; n++){
                    isPrimenumber = isprime(n);

                 if (isPrimenumber == true)
                    cout << n << " true" << endl;}}

}
                    
return 0;

}

bool isprime(int n){
    bool result = true;
        if (n < 2){
            result = false;
        } else {
            int start = 2;
            int stop = sqrt(n);
                
                for (int d = start;  d <= stop; d++){

                 if (n % d == 0){
                    result = false;
                    break; }
            }

        }
        return result;
}
First remove the loop on line 28. It really doesn't make sense. Then add a variable that is increased when n is actually prime..
Last edited on
So something along the lines of this,

although I have defiantly messed this up somewhere.

im not sure if its reading the file and going through the equation. Im not getting any errors although Im also not getting any results.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if(fin.is_open()){
    double n;
    while (fin >> n){
      double result;  
            isprime(n);
            {
                 if (result == true){
                    n++;
                    cout << n;
                    
                    
                }
                    
                    
             }
                 
    }

}


I feel like i just forgetting something super simple here. This function now counts the prime numbers but I am having trouble just getting it to give me a total of all the times prime was true.

1
2
3
4
5
6
7
8
9
10
11
double result;  
            isprime(n);
            {

                 if (result == true){
                    n++;
                
                }
                
                cout << n << endl;     
                    

}

Topic archived. No new replies allowed.