我在c中编写了一个简单的计算器,用户输入两个数字,然后选择要应用的操作。(Mul,Add,Div,Sub)程序可以正常工作,但它会跳过它应该采取的部分操作数的用户输入。我做错了什么
#include<stdio.h>
#include<sstream>
#include<iostream>
#include<conio.h>
#include<string.h>
using std::cout;
using std::cin;
using namespace std;
int main() {
char Operative[100];
int a;
int b;
int c;
printf("Enter First Number\n");
scanf("%d",&a);
printf("Enter First Number\n");
scanf("%d",&b);
printf("\nPlease Enter Operation(M,A,D,S)");
gets(Operative);
//getline(cin,Operative);
if (Operative == "M")
{
c = a*b;
printf("Multiplication value is %d",c);
}
else if (Operative == "A")
{
c = a+b;
printf("Addition value is %d",c);
}
else if (Operative == "D")
{
c = a/b;
printf("Division value is %d",c);
}
else if (Operative == "S")
{
c = a-b;
printf("\nSubtraction value is %d",c);
}
}
答案 0 :(得分:3)
使用strcmp
比较字符串值。 ==
比较指针:
if (strcmp (Operative, "M") == 0) ...
答案 1 :(得分:0)
您必须先调用cin.ignore()
(scanf
之后,gets
之前),因为缓冲区中仍有\0
。
答案 2 :(得分:0)
您也可以使用switch
声明。
switch(operation){
case 'P':
result = a+b;
printf("%d + %d = %d", a,b,result);
.
.
.
答案 3 :(得分:0)
如果您希望使用int main()
和printf
替换,只需在scanf
中对此进行编码即可。
do {
cout << "Option 1 <<endl;
cout << "Option 2 <<endl;
cout << "Option 3 <<endl;
cin >> x;
switch (x) {
case 1:
//Your operation here
break;
case 2:
//Your operation here
break;
case 3:
//Your operation here
break;
case 4:
exit(0);
break;
default:
cout << "Input a valid option" <<endl;
}
} while(x);