I have written a code to do simple arithmetic operations which gets input from the command line. So if I wanted to do a multiplication, I would type "prog_name 2 * 3" in the terminal, which should output "Product : 6".
The problem is, all the operations work except the multiplication. After some testing, I found that the third argument(argc[2]),which is used to get the operator, is actually storing the program name. So how can I make this work?
This is the code:
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
int a, b;
if(argc != 4)
{
printf("Invalid arguments!");
system("pause");
exit(0);
}
a = atoi(argv[1]);
b = atoi(argv[3]);
switch(*argv[2])
{
case '+':
printf("\n Sum : %d", a+b);
break;
case '-':
printf("\n Difference : %d", a-b);
break;
case '*':
printf("\n Product : %d", a*b);
break;
case '/':
printf("\n Quotient : %d", a/b);
break;
case '%':
printf("\n Remainder: %d", a%b);
break;
default:
printf("\n Invalid operator!");
}
}
Actually, it is the OS the one in charge of expanding the wildcards, so it is OS-specific (the C program receives just what the OS has interpreted).
That said, in most OS if you quote the wildcard it will not be expanded
program_name 2 "*" 3
. Even better, pass the whole expression as a single parameter (program_name "2 * 3"
)This has nothing to do with C but with your shell. You need to quote
*
(and other shell special characters) if you want to be able to take them as argument. Otherwise the shell will to substiutions, in particular globbing.So you need to call your program with:
Your problem is not in your code. It is in the OS/shell. You see, the
*
in the command line expands to the directory contents so the arguments2 * 3
expands to2 dir1 dir2 file1, file2, etc...
I suggest you to use someting like "2*3" as an argument and something like
sscanf(argv[1], "%d%c%d", &a, &command, &b);