I'm writing a simple calculation program and I can't get any valid output. All I'm getting is an upside down question mark. Also, I have a prompt at the end of the program to ask the user if they would like to enter in another calculation. However, when I enter a calculation the prompt comes up twice in the console. Does anyone know why these things are happening? Lastly, I can only use getchar and putchar to handle the input and output. Thanks in advance for the help.
int addFunction( int, int);
int subtractFunction(int, int);
int multiplyFunction(int, int);
int modulusFunction(int, int);
float divideFunction(float, float);
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, result = 0;
char continuePrompt, iochar = 0, operator = 0;
do {
iochar = getchar();
getchar();
if ((iochar >= 0) && (iochar <= 20000)) {
num1 = iochar;
}
if ((iochar == '+') || (iochar == '-') || (iochar == '*') || (iochar == '/') || (iochar == '%')) {
operator = iochar;
}
if ((num1 >= 0) || ((iochar >= 0) && (iochar <= 20000))){
num2 = iochar;
}
switch (operator) {
case '+':
iochar = addFunction(num1, num2);
break;
case '-':
iochar = subtractFunction(num1, num2);
break;
case '*':
iochar = multiplyFunction(num1, num2);
break;
case '%':
iochar = modulusFunction(num1, num2);
break;
case '/':
iochar = divideFunction(num1, num2);
break;
}
putchar(iochar);
printf("Would you like to make another calulation? (y or n)");
scanf("%c", &continuePrompt);
} while (continuePrompt != 'n');
return 0;
}
int addFunction(int x, int y){
return x + y;
}
int subtractFunction(int x, int y){
return x - y;
}
int multiplyFunction(int x, int y){
return x * y;
}
int modulusFunction(int x, int y){
return x % y;
}
float divideFunction(float x, float y){
return x / y;
}
The function
getchar
and gets a character from the console andputchar
puts a character to the console. The are not general input/output functions. Your code reads like you expectgetchar
to read in decimal representations of integers andputchar
to print decimal representation of integers, but they don't work that way. Since you can only usegetchar
andputchar
, you are going to have to write your own input/output methods with them to parse your inputs and display them correctly. So, first, figure out how to parse and output integers. Then use those methods where you're expecting to read or write integers (and floats if you have to display the estimated values for division). It may help to have a helper method that actually grabs the "current" numerical string from wherever you are in the expression.