1

im trying to make C calculator app. That means there is input "x + y =" and i need to calculate the result. My problem is when user input for example "6 + 4". That means there is missing equals sign. But the program is waiting for more data. How to block scanf waiting for more data after pressing enter and just say that this input was wrong?

double x,y;
char c;      //this desires if its plus, minus ...
if(scanf("%lf %c %lf =",&x,&c,&y)!=3)
{
    printf("wrong input\n");
    return 1;
}

1 Answers1

1

How to block scanf waiting for more data after pressing enter and just say that this input was wrong?

And then what to do with that bad/partially read input? Leave it for the next scanf()? scanf() simple does not readily handle unpredictably input @Jabberwocky.

A robust approach is to read a line with fgets(), then parse it.

Code could use sscanf() and "%n", which records the scan offset, to see if scanning made it that far.

  char buf[100];
  if (fgets(buf, sizeof buf, stdin)) {
    int n = 0;
    sscanf(buf, "%lf %c %lf = %n", &x, &c, &y, &n);
    if (n == 0 || buf[n] != '\0') {
      printf("Bad input <%s>\n", buf);
    } else {
      printf("Oh happy day! <%s>\n", buf);
    }
  }

More advanced code would cope with lines longer than 100 and use strtod() to parse double.

chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213