Infinite Loop Help

This program creates an infinite loop upon starting, BUT ONLY WHEN THE PROGRAM IS STARTED AFTER AN INCORRECT INPUT IS USED.

So example, I run the program and use 1, then input a correct input anfter I'm prompted to. Then when I start the program again, it loops instantly.

If I start it again, it works fine.

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

int main()
{
  double sum(0);  //sumnation
  double k;       //number used to calculate series
  double n(2);    //input

  cout<<"Enter n: ";
  cin >> n;
  

  while(n <= 1)
    {
      cout <<"Input must be greater than 1."<<endl;
      cout<<"Enter n: ";
      cin >> n;
    }
  for(k = 1;k <= n;k++)
    {
      sum += (pow(-1,k + 1))/(k);
    }

  cout <<"The alternating series converges to "<< sum <<endl;


  return(0);
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    double n = 0.0;
    while( (std::cout << "Enter n: ") &&
           (!(std::cin >> n) || n <= 1.0) )
    {
        std::cout << "Please input a value greater than 1.0\n" << std::endl;

        //these next two lines clear cin of any fail state and flush the stream
        //you could type letters when prompted for n if you wanted, and it won't crash the program
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    //at this point, you should have a valid n
    std::cout << n <<std::endl;
    //for(k = 1;k <= n;k++) ... rest of code 
Last edited on
I didn't get an infinite loop when I tried this. Sorry, I don't see what the problem is there.

As an aside, I believe both k and n should be integers, as they each represent an integer quantity. You may need to put pow(-1.0,k + 1).

However (second aside), since this loop may require many (I mean millions) of iterations, there are much more efficient ways to do this. One is to check whether k is even, and add or subtract 1.0/k accordingly, or use a variable with the initial value of 1.0 as the numerator, and negate it each time.
example:
1
2
3
4
5
6
    double numerator = 1.0;
    for (int k = 1; k <= n; k++)
    {
        sum += numerator / k;
        numerator = -numerator;
    }
When you feed cin an invalid string the read fails and it goes into an error state which causes all subsequent reads to fail.

istream::clear() clears the error flag (it's inherited from basic_ios.)

istream::ignore() skips all the remaining chars on the defective line (so the next read doesn't try to carry on from there the last error occured.)

Andy

http://www.cplusplus.com/reference/ios/basic_ios/clear/
http://www.cplusplus.com/reference/istream/istream/ignore/

Also, the problem of how to prevent non-numeric strings from unsetting extraction of ints using cin has been discussed in any number of threads. For example, here (esp. cire's post):

Trying to limit input to int type
http://www.cplusplus.com/forum/beginner/108849/#msg592118

Also see my demo of why cire's approach is better than the usual clear/ignore approach

(as part of) quadratic solver prt 2
http://www.cplusplus.com/forum/beginner/112785/#msg616197
Last edited on
Patches, there are no issues, your program runs fine. I ran it using Visual Studio 10, and no errors, and it does its job perfectly.

I added a system("pause"); right before return to pause it so that I can see the output.

**Not recommended due to it being a Windows thing.
Topic archived. No new replies allowed.