while()中关于isalpha()的琐碎内容

trivial regarding isalpha() in while()

本文关键字:while isalpha      更新时间:2023-10-16

不要介意我使用的标题数量太多。我只是复制了我遇到问题的代码片段,并包含了每个标题,因为这不会造成伤害。

我做了一个简单的检查,看看用户输入的预期整数是否不是字符。如果用户输入一个字符,它们将被带回到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]

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

本页解释了这一切,并提供了一个正确处理这种情况的代码片段:

#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;       
}