I have an assignment in which I have to input dimensions of the first matrix, then which operation i would like to perform(‘-‘, ‘+’ or ‘*’; subtraction, addition and multiplying respectively), and after that dimensions of the second matrix. But after entering first dimensions, I receive error message related to char. I cannot figure it out, even after reading a lot about whitespaces and errors related to scanf. Please help. Thank you
int main(void){
int rows_1 = 0, columns_1 = 0; //MATRIX_1 DIM
int rows_2 = 0, columns_2 = 0; //MATRIX_2 DIM
char c = ' ';
if(scanf("%d %d", &rows_1, &columns_1)!=2) //input first size
{
fprintf(stderr, "Error!\n");
return 100;
}
scanf("%c", &c);
if( c!='*' || c!='-' || c!='+' ) //error handling for char
{
fprintf(stderr, "Error!\n");
return 100;
}
if(scanf("%d%d", &rows_2, &columns_2)!=2) //input second size
{
fprintf(stderr, "Error!\n");
return 100;
}
return 0;
}
>Solution :
You have two problems:
-
The first is that
cwill contain the newline you pressed after the input forrows_1andcolumns_1. Add a single leading space in the format string:" %c"to skip leading white-space (like newlines). -
The second issue is that the logical condition is wrong and will always be
true, no matter the input forc.You probably want the opposite of
c=='*' || c=='-' || c=='+', which according to De Morgan’s laws isc!='*' && c!='-' && c!='+'(but you can also use the logical negation operator!as in!(c=='*' || c=='-' || c=='+')).This is rather easy to figure out if you think about it for a little. Lets say that
cis a newline'\n'. Thenc!='*'is true and due to the short-circuit evaluation of the logical operators, the remaining condition will not be evaluated. The same happens for any other character, including the ones you check for (exchange the newline for e.g.'-'andc!='*'will still be true; also try with'*'and thenc!='*'will be false butc!='-'will be true).