I am trying to learn c Language , I have to creat a calculator , the thing is, if I dont type anything and just press the enter key it schould print out error, I have tried to do it with scanf but it is not working.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float a,b,c;
char op;
int q=1;
while(q=1){
scanf("%f%c%f",&a,&op,&b);
if (scanf("%f%c%f",&a,&op,&b)=='\n')
{
printf("error");
}
switch (op)
{
case ' ':c=a b;
break;
case '-':c=a-b;
break;
case'*':c=a*b;
break;
case'/':c=a/b;
break;
default:printf("error");
q=2;
break;
}
{printf("%f\n",c);}
}}
CodePudding user response:
Try to scan for a newline using a scanset %1[\n]
.
Another scanset %*[^\n]
will scan and discard everything that is not a newline.
Another approach would be to use fgets
to read a line and then parse the line with sscanf
.
#include <stdio.h>
#include <stdlib.h>
int main ( void) {
char newline[2] = "";
char op = 0;
int scanned = 0;
double a = 0.0;
double b = 0.0;
double c = 0.0;
while ( 1) {
printf ( "input a number, an operator and a number\n");
printf ( " or just enter to quit\n");
if ( 1 == scanf ( "%1[\n]", newline)) { // try to scan a newline
printf ( "done\n");
break;
}
if ( 3 != ( scanned = scanf("%lf %c%lf", &a, &op, &b))) {
printf ( "bad input error\n");
printf ( "try again\n");
}
if ( EOF == scanned) {
printf ( "EOF error\n");
break;
}
scanf ( "%*[^\n]"); // scan and discard up to newline
scanf ( "%1[\n]", newline); // scan a newline
if ( 3 == scanned) {
switch (op) {
case ' ':
c = a b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
break;
default:
printf ( "bad op error\n");
printf ( "try again\n");
op = 0;
break;
}
if ( op) {
printf ( "%f\n", c);
}
}
}
return 0;
}