Looping issue

My program asks for a filename and then calls this code. I have a test file that is 7 pairs of integers: 1 1, 6 11, 3 3, 10 16, 7 10, 8 9, 1 16. When I run this, it reads the pairs as 1 6, 11 3, 3 10, 16 7, 10 8, 9 1, 16 1. In other words, it skips the first integer but adds it to the end. The file is set up as integer space integer character return integer space integer etc.

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef CHECK_H_
#define CHECK_H_

#include <iostream>
#include <fstream>

#include "math.h"

using namespace std;

bool isPrime ( int num )
{
    if ( num <= 1 )
	{
        return false;
	}
    else if ( num == 2 )
	{
        return true;
	}
    else if  ( num % 2 == 0 )
	{
        return false;
	}
    else
    {
        bool prime = true;
        int divisor = 3;
        double num_d = static_cast<double>( num );
        int upperLimit = static_cast<int>( sqrt(num_d) + 1 );
        
        while ( divisor <= upperLimit )
        {
            if ( num % divisor == 0 )
			{
                prime = false;
			}
            divisor += 2;
        }

        return prime;
    }
}

void doCalculation ( istream & infile )
{
	while ( true )
	{
		int a, b, i, primecount = 0;

		if ( infile.fail() )
		{
			break;
		}

		infile >> a >> b;
		for ( i=a; i<=b; i++ )
		{
			if ( isPrime(i) )
			{
				primecount++;
			}
		}

		cout << a << "    " << b << "  primes: " << primecount << endl;
	}
}

void checkFile ( istream & infile )
{
	string tempString;

	if ( infile >> tempString )
	{
		doCalculation ( infile );
	}
	else
	{
		cout << endl << "primes: 0  The file you entered is empty" << endl;
	}
}

#endif 
Last edited on
Topic archived. No new replies allowed.