Advertisement
Laurelai

Untitled

Jul 30th, 2011
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. // simple calculator using sscanf and fgets
  2. // gcc -o calc calc.c
  3. //
  4.  
  5. #include <stdio.h>
  6.  
  7. // an invalid expression was supplied let the user know
  8. void invalid()
  9. {
  10.     printf("invalid expression\n");
  11.        
  12. }
  13.  
  14. int main(int argc, char **argv)
  15. {
  16.     int x, y, z;        // storage for our values
  17.     int line = 0;       // current line number
  18.     char op;        // operator from the user
  19.         char buf[20];
  20.         printf("Press ctrl-c to exit\n");
  21.  
  22.     // continue processing user input until SIGINT
  23.     while(1)
  24.     {
  25.         line++;             // increment line number
  26.         x = y = z = op = 0;     // reset our storage
  27.         printf("%d> ", line);       // print a REPL prompt to the terminal
  28.                 fgets(buf, 20 - 2, stdin);      // fixed the memory error
  29.             sscanf(buf, "%d %c %d", &x, &op, &y); // read the expression from the terminal
  30.  
  31.         // test that the expression is valid
  32.         if(x < 0 || op == 0 || y < 0)
  33.                
  34.                
  35.         {
  36.             // try again
  37.             invalid();
  38.             continue;
  39.         }
  40.  
  41.         // evaluate the expression based on it's infix operator
  42.         switch(op)
  43.         {
  44.             case '+':
  45.                 // add
  46.                 z = x + y;
  47.                 break;
  48.             case '-':
  49.                 // subtract
  50.                 z = x - y;
  51.                 break;
  52.             case '*':
  53.                 // multiply
  54.                 z = x * y;
  55.                 break;
  56.             case '/':
  57.                 // divide
  58.                                 if ( y == 0)
  59.                        {
  60.                     // you can't divide by zero.
  61.                     invalid();
  62.                     continue;
  63.                }
  64.                 z = x / y;
  65.                             break;
  66.             case '^':
  67.                 // xor
  68.                 z = x ^ y;
  69.                 break;
  70.             default:
  71.                 // invalid
  72.                 invalid();
  73.                 continue;
  74.         }
  75.         // print the result to the terminal
  76.         printf("%d\n", z);
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement