Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I'm trying to make a simple program in C that takes these arguments: math.exe (first number) (math operator, like +, -, etc)(second number). The program compiles fine but, doesn't work at all. Here's my source code:
#include (stdio.h)
#include (stdlib.h)
int main(int argc, char *argv[])
{
float num1, num2, answer;
while(argc < 3)
{
printf("\n\nUSAGE: add <first number> <operator> <second number>\n\n");
exit(1);
}
num1 = atof(argv[1]);
num2 = atof(argv[2]);
if(argv[3] == "+")
{
answer = num1 + num2;
printf("%f + %f = %f",num1,num2,answer);
}
else if(argv[2] == "-")
{
answer = num1 - num2;
printf("%f - %f = %f",num1,num2,answer);
}
else if(argv[2] == "/")
{
answer = num1 / num2;
printf("%f / %f = %f",num1,num2,answer);
}
return 0;
}

Hi,
you need to use if(strcmp(argv[3],"+")==0) instead of == operator.
Here is the working program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
float num1, num2, answer;
while(argc < 3)
{
printf("\n\nUSAGE: add <first number> <second number> <operator>\n\n");
exit(1);
}
num1 = atof(argv[1]);
num2 = atof(argv[2]);
if(strcmp(argv[3],"+")==0)
{
answer = num1 + num2;
printf("%f + %f = %f",num1,num2,answer);
}
else if(strcmp(argv[3],"-")==0)
{
answer = num1 - num2;
printf("%f - %f = %f",num1,num2,answer);
}
else if(strcmp(argv[3],"/")==0)
{
answer = num1 / num2;
printf("%f / %f = %f",num1,num2,answer);
}
else
{
printf("\n\nUSAGE: add <first number> <second number> <operator>\n\n");
exit(1);
}
return 0;
}--
mohameda@ieee.org

Oh, I see now! I forgot that the elements stored in argv were strings. Thank you very much for the help!

printf("\n\nUSAGE: add <first number> <operator> <second number>\n\n");
num2 = atof(argv[2]);
if(strcmp(argv[3],"+")==0)Hmm....
BlueRaja.admin@gmail.com

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |