c++ - 我的计算器代码中有一个错误,我现在不知道如何修复它
问题描述
当我们将这封信插入控制台时,它开始在第 19 行和第 42 行重复。当我通常写发票时,它对我有用。
请帮助如何解决这个问题。
#include<iostream>
using namespace std;
int main()
{
float num1, num2;
char operator1;
bool repeat = true;
while (repeat)
{
char odgovor; //odgovor da ali ne v katerega bom spravil v bool(true / false)
cout << "do you want to continue d(yes) or n(no) " << endl;
cin >> odgovor;
repeat = odgovor == 'd';
cout << "enter the calculation" << endl;
cin >> num1 >> operator1 >> num2; //vnos dveh števil in operatorja
switch (operator1)
{
case'-':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 - num2 << endl; break;
case'+':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 + num2 << endl; break;
case'/':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 / num2 << endl; break;
case'*':cout << num1 << " " << operator1 << " " << num2 << " = " << num1 * num2 << endl; break;
case'%':
bool isNum1Int, isNum2Int;
isNum1Int = ((int)num1 == num1);
isNum2Int = ((int)num2 == num2);
if (isNum1Int && isNum2Int)
{
cout << (int)num1 << " " << operator1 << " " << (int)num2 << " = " << (int)num1 %(int)num2 << endl; break;
}
else {
cout << "the number must be an integer" << endl; break;
}
default:cout << "not valid" << endl; break;
}
}
return 0;
}
解决方案
当我们将字母插入控制台时,它开始在第 19 行和第 42 行重复。
这条线是罪魁祸首:
cin >> num1 >> operator1 >> num2;
在这里,std::cin
将首先尝试从控制台读取一个整数。如果你正确输入一个整数,什么都不会发生,一切都会按预期进行。
但是,当您仅将一个字符传递给控制台时,会std::cin
失败,因为它无法在您的输入中找到一个整数。失败后std::cin
,它不会尝试阻止执行以获取更多输入,此外,您的代码中没有任何内容会跳出while
循环,因此它将无限期地迭代,这就是您所面临的。
要解决此问题,您可以检查是否std::cin
失败并在需要时相应地中断循环:
// ...
cin >> num1 >> operator1 >> num2;
if (cin.fail())
break; // Break out of the loop in case of failure
// ...
推荐阅读
- java - 修改 Jar 中的静态资源
- java - 无效值 java.sql.SQLException:应用程序请求者无法建立连接
- autodesk-forge - Autodesk Forge 设计自动化 API 和 Vault
- django - inlineformset - 递增 TOTAL_FORMS 给出 MultiValueDictKeyError
- javascript - 在for循环javascript中调用函数
- iis - 增加“连接超时(秒)”(IIS)有什么风险?
- c# - 如何按类型正确地将对象从 C# 传递到 VBScript?
- c# - 简单注入器注入 PageModel ASP.NET Core Razor 页面
- xml - 单个元素下的多个 xs:id 属性 - XSD 定义
- git - 如何使用 git log 显示远程 refs/notes/*