关于while()中isalpha()的微不足道

时间:2014-04-25 21:06:57

标签: c++ loops while-loop

不要介意我正在使用的标题数量不明确。我只是在复制我遇到问题的代码的snippit,并且包含了每个标题,因为它不会受到伤害。

我正在进行一个简单的检查,看看预期整数的用户输入是否不是一个字符。如果用户输入一个字符,它们将返回到while循环的开头,直到输入一个整数。

      while (edgeLength<4 || edgeLength>12)
    {
      //...
    }

这样可确保输入4到12之间的数字,并按预期工作。

我的问题:

为什么当我输入任何字符时,说'x',while循环的内容无限循环? 我指定isalpha(edgeLength)作为要注意的条件,但没有运气。

#include <math.h>   // for exponents
#include <iostream> // for cout<< and cin>>
#include <stdlib.h> // for exit() and rand()
#include <ctype.h>  // for conversion to upper case and isalpha
#include <time.h>   // for seeding random generator
#include <iomanip>  // for formatting the board (setw)
using namespace std;

int main()
{
int edgeLength;
cout<<"Enter the size board you want, between 4 and 12: ";
  cin>>edgeLength;


  while (edgeLength<4 || edgeLength>12 || isalpha(edgeLength))
      {
      cout<<"Invalid size.   Choose a value between 4 and 12: ";
      cin>>edgeLength;
      }
      return 0;

}

当前输出:

Enter the size board you want, between 4 and 12: e
Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:Invalid size.   Choose a value between 4 and 12:
    ...
    ...
    ...

期望的输出:

Enter the size board you want, between 4 and 12: e
Invalid size.   Choose a value between 4 and 12: 5
[process returns 0]

1 个答案:

答案 0 :(得分:3)

当cin期望一个int,但输入无法转换为int时,它会失败并将输入数据留在流中。所以,如果你循环,你会一遍又一遍地读取相同的数据,每次都无法将其转换为int。请注意,cin&gt;&gt;如果转换失败,edgeLength返回false,因此您可以测试它。

This page解释了这一切,以及正确处理这种情况的代码段:

#include<iostream>
#include<limits>

using namespace std;
int main()
{

    cout << "Enter an int: ";
    int x = 0;
    while(!(cin >> x)){
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You entered: " << x << endl;       
}