您好我刚开始学习C ++而我正在尝试制作一个计算器,现在有一个我不知道如何在C ++中修复的fue问题。
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cout << "1. Saskaitiissana(+)" << endl;
cout << "2. atnnemssana(-)" << endl;
cout << "3. daliissana(/)" << endl;
cout << "4. reizinaassana(*)" << endl;
cin >> d;
switch(d){
case 1 :
cout << "ievadiet a un b lai saskaitiitu(+)" << endl;
cin >> a;
cin >> b;
c = a + b;
cout << "The sum of number 1 and number 2 is " << c << "\n" <<endl;
break;
case 2 :
cout << "ievadiet a un b lai atnnemtu(-)" << endl;
cin >> a;
cin >> b;
c = a - b;
cout << c << endl;
break;
case 3 :
cout << "ievadiet a un b lai reizinaatu(*)" << endl;
cin >> a;
cin >> b;
c = a * b;
cout << c << endl;
break;
case 4 :
cout << "ievadiet a un b lai dal'itu(/)" << endl;
cin >> a;
cin >> b;
if(b==0)
{
cout<<"Nulle neder! start over."<<endl;
}
c = a/b;
cout << c << endl;
break;
}
return 0;
}
我还要做的事情。 找到程序仅使用数字的最简单方法。此外,当我输入一个数字时,它不能是#34;空格&#34;。 另外,如何在完成后制作表壳并给出结果,回到开始菜单的开头?如果我要退出程序,请按esc或5?
还有退出选项,我正在考虑使用do&#34; 5&#34;是按下,可以在c ++中工作吗?
现在我最感兴趣的是如何检查程序只使用数字,并且在添加数字时没有空格。
感谢您的时间:)
答案 0 :(得分:2)
要忽略非数字输入,您可以使用以下代码:
std::cin >> d;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> d;
}
或以C风格:
while(scanf("%i",&d)!=1)
{
fseek(stdin,0,SEEK_END);
}
您还可以将一大堆代码放在while
语句中,以便在一次操作后重新运行计算器。
答案 1 :(得分:1)
考虑到安全输入:
//----------------------------------------------------------------------------
#include <iostream>
using namespace std;
//----------------------------------------------------------------------------
void SafeDouble (double &d)
{
while (!(cin >> d))
{ cin.clear();
while (cin.get() != '\n');
cout << "\tIncorrect. Try again\n\t";
}
cin.sync();
}
//----------------------------------------------------------------------------
int main()
{
cout << "The simpliest calculator\n";
double a = 0.,b = 0.;
cout << "\na = ";
SafeDouble (a);
cout << "b = ";
SafeDouble (b);
cout << "\nEnter operation sign: +, -, * or /\n";
char op;
cin >> op;
cin.sync();
switch (op)
{
case '+': cout << a << " + " << b << " = " << a + b;
break;
case '-': cout << a << " - " << b << " = " << a - b;
break;
case '*': cout << a << " - " << b << " = " << a * b;
break;
case '/': if (b == 0.0)
cout << "Division by zero";
else
cout << a << " / " << b << " = " << a / b;
break;
default: cout << "Incorrect operation sign";
}
cin.get();
return 0;
}
//-----------------------------------------------------------------------------