0

Hi. I wrote a calculator that calculates the given expression (eg, 2 +3 +4-3-1), it works only if you type expression and press ctrl-d, what i have to do to display the result after pressing enter
Here's the code:

#include <stdio.h>

int main()
{
        printf("give expression \n");
        char expression;
        int x,y;
        scanf("%d",&x);
        
        while (scanf("%c %d",&expression,&y) !=EOF) 
        {                                               
                        if (expression == '+')
                                x+=y;
                        if (expression == '-')   
                                x-=y;                                                                   
        }
        
printf("\n %d\n",x);
        return 0;
}

I thought to change

while (scanf("%c %d",&wyrazenie,&y) !=EOF)

to

while (scanf("%c %d",&wyrazenie,&y) !='\0')

but then the result does not show.

Sorry for my English.

2
Contributors
2
Replies
5
Views
6 Years
Discussion Span
Last Post by Thoronath
0

How about a new line 11 1/2:

if(expression=='q') 
   break;

You should have a getchar() in your code, (maybe line 11 3/4ths, to remove the newline that scanf() always leaves behind.

Edited by Adak: n/a

0

Do you mean:

#include <stdio.h>

int main()
{
	printf("podaj wyra┼╝enie \n");
	char wyrazenie;
	int x,y;
	scanf("%d",&x);
	scanf("%c %d",&wyrazenie,&y);
	while (getchar() !='\n') 
	{						
			if (wyrazenie == '+')
				x+=y;
			if (wyrazenie == '-')	
				x-=y;						
	}
		printf("\n %d\n",x);	

	return 0;
}

Now if I type eg 2+2+3+4, result = 10

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.