while()中关于isalpha()的琐碎内容
trivial regarding isalpha() in while()
不要介意我使用的标题数量太多。我只是复制了我遇到问题的代码片段,并包含了每个标题,因为这不会造成伤害。
我做了一个简单的检查,看看用户输入的预期整数是否不是字符。如果用户输入一个字符,它们将被带回到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;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- while()中关于isalpha()的琐碎内容