如何将输入限制为仅数字
How to Limit Input to Numbers Only
我最近创建了一个程序,该程序将根据用户输入创建一个数学问题。 通过输入 1-4,程序可以生成问题,或者用户可以通过输入 5 退出。 我遇到的唯一问题是,当我输入一个字符时,程序会进入无限循环。 我可以使用什么功能来检查输入是否不是数字,以便我可以显示错误消息?
//CIS180 Assignment #4
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
//Declare variables.
int num1, num2, menuNum;
int addInput, subInput, multInput, divInput;
int addAnswer, subAnswer, multAnswer, divAnswer;
int addSolution, subSolution, multSolution, divSolution;
srand(time(0));
//Display menu.
cout << "Menu" << endl;
cout << "1. Addition problem" << endl;
cout << "2. Subtraction problem" << endl;
cout << "3. Multiplication problem" << endl;
cout << "4. Division problem" << endl;
cout << "5. Quit this program" << endl << endl;
cout << "Enter your choice (1-5): " << endl;
cin >> menuNum;
//Loop that will provide math problems when user inputs number.
while(menuNum != 5)
{
//Check if the input is valid.
while((menuNum < 1) || (menuNum >5))
{
cout << "The valid choices are 1, 2, 3 , 4, and 5. Please choose: " << endl;
cin >> menuNum;
}
//Generate two random numbers for addition and display output.
if(menuNum == 1)
{
num1 = rand()%500 + 1;
num2 = rand()%500 + 1;
addSolution = num1 + num2;
cout << setw(5) << right << num1 << endl;
cout << setw(2) << left << "+" << setw(3) << right << num2 << endl;
cout << setw(5) << fixed << "-----" << endl;
cin >> addAnswer;
//Check if the addition answer input is correct.
if(addAnswer != addSolution)
cout << "Sorry, the correct answer is " << addSolution << "." << endl;
else if(addAnswer == addSolution)
cout << "Congratulations! That's right." << endl << endl;
}
.
.
.
首先,您应该检测您的输入尝试是否成功:请务必在读取后检查读取尝试是否成功。接下来,当您确定无法读取值时,您需要使用 clear()
将流重置为良好状态,并且您需要删除任何不良字符,例如使用 ignore()
.鉴于字符通常是输入的,即用户必须在使用字符之前点击回车键,因此通常可以获取整行。例如:
for (choice = -1; !(1 <= choice && choice <= 5); ) {
if (!(std::cin >> choice)) {
std::cout << "invalid character was added (ignoring the line)n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
}
使用std::numeric_limits<std::streamsize>::max()
是获取幻数的方法,它使ignore()
尽可能多的字符,直到找到具有第二个参数值的字符。
- 读取单个字符
- 如果此字符是数字,请使用它。
- 如果此字符不是数字,请转到 1。
实际上,忘记步骤2。只需检查它是否是您实际想要的数字字符之一('1'
,'2'
,'3'
,'4'
,'5'
):
char choice;
while(cin.get(choice)){
if(choice == '5')
break;
switch(choice){
default: printWrongCharacterMessage(); break;
case '1': do1Stuff(); break;
case '2': do2Stuff(); break;
case '3': do3Stuff(); break;
case '4': do4Stuff(); break;
}
}
你可以使用 ctype.h 中的 isdigit
相关文章:
- 从C++中的数字输入动态创建矩阵
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 非数字输入检查
- C++和 XAML - 来自文本框的数字输入
- 该代码不会在其中显示任何数字输入.如何使它显示任何输入
- 如何从数字输入文件中查找最大数字
- C++ 将数字输入数组并输出
- 无法从字符串获取数字输入
- 输入数字输入到if语句中
- C++数字输入的输入验证
- 来自单个数字输入的Arduino读取脉冲宽度频率和占空比
- 如何区分数字输入和字母输入
- 为什么我的程序取消了更多的数字输入
- C++:运行程序时出现分段错误(将文件中的数字输入数组)
- C++:使用for循环允许用户将数字输入到数组中
- C++ - 如何将空格分隔的数字输入数组
- _wtoi返回零:输入零或非数字输入
- 数字输入的输入验证
- 为什么我随机生成的数字输入都是零
- 我需要让一个数字输入的用户输出单个数字使用c++