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
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;
}
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):