我是一个非常新手的程序员,所以我不太了解如何编写代码来保护应用程序。基本上,我创建了一个 basicMath.h 文件并创建了一个 do while 循环来制作一个非常基本的控制台计算器(只有两个 float 通过函数传递)。我使用一系列 if 和 else if 语句来确定用户想要执行的操作。 (1.add, 2.subtract, 3.multiply, 4.divide) 我使用了 else { cout << "invalid input"<< endl;} 来防止任何其他值,但后来我尝试实际写一封信,程序进入无限循环。是否有办法防止用户意外击中字符而不是数字?
`#include <iostream>
#include "basicMath.h"
using namespace std;
char tryAgain = 'y';
float numOne = 0, numTwo = 0;
int options = 0;
int main()
{
cout << "welcome to my calculator program." << endl;
cout << "This will be a basic calculator." << endl;
do{
cout << "What would you like to do?" << endl;
cout << "1. Addition." << endl;
cout << "2. Subtraction." << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division." << endl;
cin >> options;
if (options == 1){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " + " << numTwo << " = " << add(numOne, numTwo) << endl;
}
else if (options == 2){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " - " << numTwo << " = " << subtract(numOne, numTwo) << endl;
}
else if (options == 3){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " * " << numTwo << " = " << multiply(numOne, numTwo) << endl;
}
else if (options == 4){
cout << "Enter your first number." << endl;
cin >> numOne;
cout << "Enter your second number." << endl;
cin >> numTwo;
cout << numOne << " / " << numTwo << " = " << divide(numOne, numTwo) << endl;
}
else {
cout << "Error, invalid option input." << endl;
}
cout << "Would you like to use this calculator again? (y/n)" << endl;
cin >> tryAgain;
}while (tryAgain == 'y');
cout << "Thank you for using my basic calculator!" << endl;
return 0;
}
`
最佳答案
一种方法是使用异常处理,但作为新手,您可能还远远没有学会这一点。
而是使用 cin.fail()
,它在错误或意外输入后返回 1。请注意,您需要使用 cin.clear()
清除“bad”状态。
一个简单的方法是实现一个函数:
int GetNumber ()
{
int n;
cin >> n;
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Not a valid number. Please reenter: ";
cin >> n;
}
return n;
}
现在,在主函数中,无论您在何处获取输入,只需调用 GetNumber
并将返回值存储在变量中即可。例如,不要使用 cin >> numOne;
,而是 numOne = GetNumber();
关于c++ - 如何避免用户输入错误的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22573235/