0

I'm writing a program where the user can input a number with an arithmetic operator, and then I find out which arithmetic operator it is and print it. For ex- 123456+123456 --> Opertor present is: '+'

I can't figure out how to identify the operator in the user input.

Here's my code:

#include<stdio.h>
#include<string.h>

char numberArray1[50];
int i=0,lengthofFirstNumber;

int inputforCalculator(){
    //Variable declaration
    char operator;

    //Will stay here always
    printf("Calc>");

    //Getting input from user
    gets(numberArray1);       

    doArithmeticOperations(numberArray1);
}
 
int doArithmeticOperations(){
    char operator;
    lengthofFirstNumber=strlen(numberArray1);
    int i=0;
    for(i=0;i<lengthofFirstNumber;i++){
        puts(numberArray1);

        //THIS PART IS NOT WORKING
        if(operator == '+' ){
            printf("Operator is present.");
            break;
        }
        else{
            printf("Invalid Input.");
            break;
        }
    }
}

int main(){
    char operator;
    inputforCalculator(numberArray1[0],numberArray2[0]);        
    return 0;
}
  • Read each character of the input until a non-numeric value is found. That's the potential operator so at that point you can check for valid operator characters. – kaylum Aug 24 '21 at 04:51
  • As long as you commit to integer numbers, `strtol()` may help. Otherwise, you need a full-blown expression parser. – DYZ Aug 24 '21 at 04:54
  • 2
    Don't use `gets` and don't use globals when you don't need to. Also, you may find `strspn` useful to get past all the digits. – mediocrevegetable1 Aug 24 '21 at 05:06
  • Each of those `char operator;` is local to the function in which it is declared. In the one function where it is used, it isn't initialized or otherwise assigned to before reading which will cause *undefined behaviour*. A `break` in both branches of your conditional means that loop with never pass the first iteration. The global `i` is unused. Your functions are given arguments that don't match their signatures and don't return their expected type. `doArithmeticOperations` is used before being declared. `numberArray2` is not defined anywhere. This should/will not compile. – Oka Aug 24 '21 at 05:25
  • 1
    Read: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Oka Aug 24 '21 at 05:27

0 Answers0