Hi. I need help for a school project. I need to creat a calculator program using only getchar and putchar. the user has to enter the statement and the program should echo the statement and the answer. for example the user has to enter " 3 + 6 " and the program should answer " 3 + 6 = 9".
I appreciate any help.
here is what I have. and I have no idea what's wrong.
Code:
#include <stdio.h>
#include <math.h>
char Cont (void);
int isdigit1 (char C);
int Convert(char );
int main(void)
{
int Error = 0 , Num1 , Num2, Oper;
char Flag, c;
double Result;
do
{
while ( ( c=getchar() ) != EOF)
{
if ((c == ' ') || (c = '\t'))
{
putchar(c);
continue;
}
if /*while*/ (isdigit1 (c))
{
Num1 = Convert(c);
}
if ((c=='+') || (c=='-') || (c=='*') || (c=='/') || (c=='%'))
{
switch (c)
{
case '+':
Oper = 1; // current month days
break;
case '-':
Oper = 2;
break;
case '*':
Oper = 3;
break;
case '/':
Oper = 4;
break;
case '%':
Oper = 5;
break;
}
putchar (c);
}
if /*while*/ (isdigit1 (c))
{
Num2 = Convert(c);
}
switch (Oper)
{
case 1:
Result = (double)(Num1 + Num2);
break;
case 2:
Result = (double)(Num1 - Num2);
break;
case 3:
Result = (double)(Num1 * Num2);
break;
case 4:
Result = (double)(Num1 / Num2);
break;
case 5:
Result = (double)(Num1 % Num2);
break;
}
printf (" = %.2f", Result);
Flag = Cont();
}
}while ((Flag == 'y') || (Flag == 'Y') );
return 0;
}
int Convert (char c)
{
int ch,
sum = c - '0';
while ((( ch = getchar() ) != ' ' ) && (ch != '\n' ))
{
if ( !isdigit1 (ch) )
break;
sum = sum *10 + ( ch - '0');
putchar(ch);
}
return (sum);
}
int isdigit1 (char C)
{
if ((C>= '0') && (C<= '9'))
return 1;
return 0;
}
char Cont ()
{
char Flag;
printf ("******************\nWould you like to continue?\nEnter y for yes, Anything else for no.\n");
scanf ("%c%*c", &Flag);
return Flag;
}