# Thread: very simple calculator

1. ## very simple calculator

I hope you guys can help me with this calculator program that i wrote
this programming stuff is still new to me and i cant figure out why it wont the way i want it too forgive me if its something stupid. its supposed to take in to continually give an answer to the problem but it gets stuck on the first answer any help is appreciated.

Code:
```#include <stdio.h >
#include <stdlib.h>

int main(){
int l=0, l1=0;
float f1, f2,f3;
char op, op1;

printf("please enter  a problem:\n\n");

while(l==0){

//inputs
if( l1 == 0 )scanf("%f",&f1);
scanf("%c",&op);
if(op != '=')scanf("%f",&f2);

// calculatons
if(op == '+' ){f1 = f1+f2;}
if(op == '-' ){f1 = f1-f2;}
if(op == '*' ){f1 = f1*f2;}
if(op == '/' ){f1 = f1/f2;}
if(op == '=' ){     l=1;}
// output
l1 = 1;
printf("%f",f1);}

system("pause");
return(0);}```

2. put your code in a for loop like this:

Code:
```for(;;)
{
//input, output etc.}```

3. It's probably getting stuck because there is a \n character entered into the input stream when you hit enter, after typing 3+4. You need to clear that. There's a FAQ, but a simple way would be to add a call to "getchar()" after you read your pieces.

A better way to do it would be to read a whole line at a time with something like fgets, then check to see if the first thing entered was =, and if not, use something like sscanf to chop it up.

Edit: To the above poster, he has a while loop. The closing braces is on the line above the "final answer" printf.

Quzah.

4. Hey N_D_E,

Welcome to the forums. No need to apologize, everyone here has been a beginner at some point.

The first problem I can spot is that you calculate the value of the operation into variable f1, and then at the end of the program you print the results from f3, which is unused and uninitialized. Probably just a typo.

5. Thanks so much for the help "getchar()" solves the problem just fine, Thanks also for the welcome and the super quick response.

Popular pages Recent additions