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.

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.