Reputation: 45
I was writing a simple calculator in c,whereby the user inputs two numbers and afterward choose the operation to apply on them.(Mul,Add,Div,Sub)The program works except it skips the part where its supposed to take user input for the operand.what am i doing wrong
#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);
}
}
Upvotes: 0
Views: 131
Reputation: 100
Just code this in your int main()
if you prefer to use printf
and scanf
you replace and everything will be ok.
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);
Upvotes: 0
Reputation: 18825
Use strcmp
to compare strings values. ==
compares pointers:
if (strcmp (Operative, "M") == 0) ...
Upvotes: 3
Reputation: 115
You can also use switch
statement.
switch(operation){
case 'P':
result = a+b;
printf("%d + %d = %d", a,b,result);
.
.
.
Upvotes: 0
Reputation: 48928
You have to call cin.ignore()
(after scanf
, before gets
) first, because there is still \0
in the buffer.
Upvotes: 0