This issue I feel is more my understanding of pointers but here goes. I am suppose to create a system program in C that performs calculations as such math operator value1 value2. Example math + 1 2. This would produce 3 on the screen. I am having troubles comparing or summing the numbers. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int ac, char* args[] )
{
int total;
if (strcmp(*++args,"+") == 0)
{
}
printf("Total= ", value1);
if (strcmp(*args,"x") == 0)
printf("multiply");
if (strcmp(*args,"%") == 0)
printf("modulus");
if (strcmp(*args,"/") == 0)
printf("divide");
return 0;
}
I can do a string compare to get the operator but am having a hard time adding the two values. I have tried:
int value1=atoi(*++args);
Any help would be appreciated.
Since you are doing a pre-increment
++
operator has higher precedence than*
so the pointer is incremented and later you are dereferencing it which case you might never get to access the arguement which you actually intend to.If you have input like
+ 1 2
We have
Why can't just access
atoi(args[2])
You can do something like
Instead of accessing the command line args via pointers, easily you can do this using array referencing. For example,
"math + 1 2"
, args[0] ismath
, args[1] will be+
etc.