Q.Create an equivalent of four function calculator. The program should request the user to enter two numbers and an operator. It should carry out specified arithmetic operation on the two numbers( using switch case).After displaying the result, the program should ask the user if he/she wants to do another calculation.If 'y', make it perform another operation.

The solution I tried

{
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c;
char sign,answer;
clrscr();
do
  {
  printf("Enter your choice of operator\n");
  printf("+ for addition\n");
  printf("- for subtraction\n");
  printf("* for multiplication\n");
  printf("/ for division\n");
  scanf("%c",&sign);
  printf("Enter two numbers\n");
  scanf("%f %f",&a,&b);
  switch(sign)
 {
 case '+': c=a+b;
    printf("The addition is %f\n",c);
                  break;
        case '-': c=a-b;
    printf("The subtraction is %f\n",c);
                  break;
 case '*': c=a*b;
    printf("The product is %f\n",c);
                  break;
        case '/': c=a/b;
    printf("The division is %f\n",c);
                  break;
 }
        printf("Do you want to continue?(y or no)\n");
 scanf("%c",&answer);
  }while(answer!='n');
}
}

Problem is that although everything else works fine, when the question "Do you want to continue ?(y or no)" is asked, it doesn't take in the answer and straight away goes ahead to provide the options again.Help!!!!!

Problem is that although everything else works fine, when the question "Do you want to continue ?(y or no)" is asked, it doesn't take in the answer and straight away goes ahead to provide the options again.Help!!!!!

That's because the char you entered is still in the buffer. It's a bug in scanf(), you shouldn't use it. Link
Also:
-the defenition of main is int main(void) -What is that bracket on the first line?
- clrscr(); isn't standard nor is Conio.h
-main should end with a return 0; -please use -codetags- the next time you post

Edited 6 Years Ago by Nick Evan: n/a

>It's a bug in scanf(), you shouldn't use it.
It's not a bug in scanf, it's a bug in the code that uses scanf. But I do agree that if you don't know how to use something, you shouldn't use it until you do.

>Try put a space before the %c
In my experience, if you say "Try <such and such>", you don't really know what's going on. If you do know that your suggestion works and why it works, please be sure to explain it so that you don't encourage inserting random characters with the "try it and see" attitude.

actually, i would recommend to use cin and cout, but i assume you are being taught to work with scanf and printf, so i will provide a secondary solution, which i wouldn't recommend to an experienced programmer...

printf("Do you want to continue?(y or no)\n");
getchar();
 scanf("%c",&answer);

i works perfectly, as i said... but i wouldn't use it myself...

>actually, i would recommend to use cin and cout
Those tend not to work in C. Judging from the code, I'd wager the OP is not using C++.

I'd wager the OP is not using C++.

there's where i will not agree... I can bet the OP is using Turbo C++...That's exactly the same kind of code they were making me use when i started on Turbo... that's why i came out with that solution... (actually that's what i did when the buffer was filled up...)

lol

come on... give me a break... where's the competition spirit?? haha (not that i would like to compete with you... i'm certain you would beat the hell out of me...)

c specification when used with scanf() functions, specifies single-byte character. White-space characters that are ordinarily skipped (in my experience the carriage return) are read when c is specified. To read next non–white-space single-byte character use %1s if you don't want to use a space as in the secure version, scanf_s() where we need to define the size explicitly. In this case the size is 1 byte. So use:

char c;
...
scanf("%c", &number, 1)

did you give the option as

printf(" do you want to continue(y or no)");

or

printf(" do you want to continue(y or n)");

char will take in only one character.....

so make sure its an n... not no...

printf(" do you want to continue(y or n)");
scanf("%c",&answer)
}while(answer!='n');

has to work....

First of all , it is a C program so I am not using cin and cout. Abt codetags, i tried using them but it didn't happen..tht explains the extra pair of brackets. Abt the question I asked it was "Do you want to continue?(y or n)"..Yes i know char accepts only single and wht u suggested Gel is exactly wht I tried but it did not work.

god!!!

i don't know why its not working for you...

i did this program in my 12th grade.. it was fine then......

let me try again...

Here is a code fragment which will assist you:

#include <stdio.h>
main()
{
#define ADD 1;
#define SUB 2;
#define MUL 3;
#define DIV 4;
 
char response[10];

char dummy[2]; /*** scanf trick buffer ***/
int first_op,
secnd_op,
operation;


/* query user */
printf("Please enter first operand.....\n");
printf("calc:==> ");
scanf("%d",&first_op);
gets(dummy);
printf("Here is the REAL value after tricking scanf:===> %d\n", first_op);
}

Do this iteration, scanf() then get(s), and you will be fine. (I had the same scanf problem in 1988)
Also, use the DEFIN

>Here is a code fragment which will assist you
I doubt it. That code is awful.

>main()
int main ( void )

>#define ADD 1;
>#define SUB 2;
>#define MUL 3;
>#define DIV 4;
Ending a macro with a semicolon is the path to disaster and cryptic error messages.

>char dummy[2]; /*** scanf trick buffer ***/
If you're using a buffer to trick scanf anyway, why not just eschew scanf in favor of something more suitable?

>printf("calc:==> ");
If you don't print a newline, you need to flush stdout. Otherwise the prompt may not be visible by the time scanf blocks for input.

>gets(dummy);
gets is evil. Don't ever use it. There are no excuses.

>}
Even though you cleverly used an implicit int in defining main, it still returns int.

Try this on for size:

#include <stdio.h>

int main ( void )
{
  char buffer[BUFSIZ];

  printf ( "Enter an expression (number operator number): " );
  fflush ( stdout );

  if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
    int a, b;
    char op;

    if ( sscanf ( buffer, "%d %c %d", &a, &op, &b ) == 3 ) {
      switch ( op ) {
      case '+': printf ( "%d\n", a + b ); break;
      case '-': printf ( "%d\n", a - b ); break;
      case '*': printf ( "%d\n", a * b ); break;
      case '/':
        if ( b != 0 )
          printf ( "%d\n", a / b );
        else
          printf ( "Cannot divide by zero\n" );
        break;
      default:
        printf ( "Unknown operation\n" );
        break;
      }
    }
  }

  return 0;
}

First of all , it is a C program

darn... that was a close one... :P

Yes i know char accepts only single and wht u suggested Gel is exactly wht I tried but it did not work.

Why don't you try reading it as a string, even though it is a char? this should end with the buffer problem... this way:

scanf("%s",&answer);

>scanf("%s",&answer);
That's a really bad idea. If answer is declared as char, you have a guaranteed buffer overflow. If answer is declared as an array of char, you have a potential buffer overflow and a type mismatch. All of them are undefined, so that line screws you over big time.

As a general rule of thumb, %s is off limits at all times.

"It works for me" is not a good reason to do something. Most of the time, if you can't prove that it's correct, it's horribly broken. ;)

I knew that you were waiting - like a shark out for blood ,just take this apart line by line.

The gets(s) following the scanf() is not at all that evil if you know how to use it.

This does work. It addresses the issue. With that in mind your comments

printf("calc:==> ");
If you don't print a newline, you need to flush stdout. Otherwise the prompt may not be visible by the time scanf blocks for input.

>gets(dummy);
gets is evil. Don't ever use it. There are no excuses.

>}
Even though you cleverly used an implicit int in defining main, it still returns int.

are superflous.

Remember, deal with the issue.....

if you can't prove that it's correct, it's horribly broken

I know it is horribly broken... actually, i wouldn't use it myself...

its just that i was in a desperate situation you know? i HAD to do it... i didn't find any other solution... :D

Erm, I dunno C, learning C++ atm, but it sounds like whatever the C equivalent of cin.ignore() would do the trick....

>I knew that you were waiting - like a shark out for blood ,just take this apart line by line.
It's enlightened self interest, I assure you. If you teach people bad habits, I have to help them unlearn those habits.

>The gets(s) following the scanf() is not at all that evil if you know how to use it.
Really. Show me how to make any call to gets safe. You can do anything you want as long as it's a code change and doesn't rely on an outside force doing the right thing.

>This does work. It addresses the issue.
It addresses the symptom of the issue, not the issue itself. The issue is that scanf is being used improperly. Cleaning up the stream after scanf is just a Band-Aid that reeks of sloppy programming.

>With that in mind your comments are superflous.
I disagree. Any code posted here can be learned from, so I would be doing everyone a disservice by letting bad code go uncorrected.

>but it sounds like whatever the C equivalent of cin.ignore() would do the trick....
Sadly, there isn't a C equivalent. You have to do the C equivalent of this to remain portable:

char c;

while ( cin.get ( c ) && c != '\n' )
  ;

actually i imagined something like that was going on... i knew that "\0" was still there...

i didn't know that for sure though... thnx...

Here is the PROOF you need.....

char response[10];
char dummy[2]; /*** scanf trick buffer ***/
int first_op,
secnd_op,
total,
operation;
 
/* query user */
printf("Please enter first operand.....\n");
printf("calc:==> ");
scanf("%d",&first_op);
gets(dummy);

printf("Please enter second operand.....\n");
printf("calc:==> ");
scanf("%d", &secnd_op);
gets(dummy);
/* perform an ADDITION operation */

total = first_op + secnd_op;
printf("Here is your TOTAL:==. %d\n", total);
}

Execution:

techRx:==> ls -l test1.c
-rw-rw-rw- 1 techrx techrx 591 May 04 16:08 test1.c
techRx:==> cc test1.c
techRx:==> a.out
Please enter first operand.....
calc:==> 33
Please enter second operand.....
calc:==> 100
Here is your TOTAL:==. 133
techRx:==>


This question has already been answered. Start a new discussion instead.