gpt4 book ai didi

c++ - 如何将输入限制为仅数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:07:18 25 4
gpt4 key购买 nike

我最近创建了一个程序,可以根据用户输入创建一道数学题。通过输入 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()的使用是获得魔数(Magic Number)的方法ignore()尽可能多的字符,直到找到具有第二个参数值的字符。

关于c++ - 如何将输入限制为仅数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18936664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com