KawaiKx
KawaiKx

Reputation: 9940

how to stop this code from hanging at wrong inputs?

I am learning C from ' programming in C' by Stephen Kochan. I am working on exercise no 4 of chapter 6 , writing a code that acts as a simple accumulator calculator. code is following. it works fine as long as inputs are provided in the right manner order.

#include<stdio.h>

    int main(void)
    {
        float num, accum = 0;

        char operator;


        while(1)

        {

          printf("Enter the number and the operator ");
          scanf("%f %c",&num, &operator);

          if (operator == 'E') break;

          switch (operator){

        case 'S':
          accum = num;
          printf("= %g\n",accum);
          break;

        case '+':
          accum = accum + num;
          printf("= %g\n",accum);
          break;

        case '-':
          accum = accum - num;
          printf("= %g\n",accum);
          break;

        case '*': 
          accum = accum * num;
          printf("= %g\n",accum);
          break;

        case '/':
          accum = accum / num;
          printf("= %g\n",accum);
          break;
          }      
        }

        printf("= %g\n",accum);
        printf("End of Calculation\n");

      return 0;

    }

but it hangs on the wrong inputs. what can be done to check such behaviour?

Upvotes: 0

Views: 221

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 186108

  1. Check that scanf() returns 2, indicating that it has populated both arguments
  2. Provide a default case in the switch statement that reports an error.

For increased robustness, you might want to read the whole line using fgets() (don't use gets() because it is vulnerable to buffer overflow) and parse the result using sscanf(). This is only necessary if you want to provide recovery from bad inputs. Otherwise, just stick with scanf() and exit(1) (and an error message) if anything goes wrong.

Upvotes: 2

geekosaur
geekosaur

Reputation: 61457

The short version is "don't use scanf()."

The problem is that scanf() provides only a limited indication of error, and leaves the erroneous data unread tp be picked up by the next call; especially if you're not bothering to do error checking, it's just going to spin forever on the bad data.

  1. Always check the return code, so you know if it worked or not.
  2. If you're doing line oriented input, use fgets() or similar to read an entire line, and sscanf() to parse from the line.
  3. Do something sensible if the input isn't what you expected, instead of just barreling on through. (Your existing code just assumes it's always valid.)

Upvotes: 6

Pavan Manjunath
Pavan Manjunath

Reputation: 28595

Dont use scanf. Thats the first sight suggestion for this program. Use something like getchar like shown here They are dealing with the same problem as yours.

Upvotes: 2

Related Questions