-1

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;
}
Leon
  • 13
  • 3

1 Answers1

1

You have two problems:

  1. The first is that c will contain the newline you pressed after the input for rows_1 and columns_1. Add a single leading space in the format string: " %c" to skip leading white-space (like newlines).

  2. The second issue is that the logical condition is wrong and will always be true, no matter the input for c.

    You probably want the opposite of c=='*' || c=='-' || c=='+', which according to De Morgan's laws is c!='*' && 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 c is a newline '\n'. Then c!='*' 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. '-' and c!='*' will still be true; also try with '*' and then c!='*' will be false but c!='-' will be true).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621