I am working on a program that takes input from the command line and then works out the math equation based on what the input was. I am using if, else if, else statments to handle the argument counts. However, if I run the program without putting input on the command line it gives me a "Segmentation Fault" error. I am wanting a custom error message that says "Input Error" which is what I am trying to use the else statement for. However, it won't display input error and only displays the segmentation fault instead.
Any suggestions are appreaciated!
Code:
/*
Jacob L. Jones
Computer Programming II
*/
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
float num1;
float num2;
float ans;
char choice;
if (argc == 4){
sscanf(argv[1], "%f", &num1);
sscanf(argv[2], "%c", &choice);
sscanf(argv[3], "%f", &num2);
switch (choice){
case '+':
ans = num1 + num2;
printf("%.2f + %.2f = %.2f\n", num1, num2, ans);
break;
case '-':
ans = num1 - num2;
printf("%.2f - %.2f = %.2f\n", num1, num2, ans);
break;
case 'x':
case 'X':
ans = num1 * num2;
printf("%.2f x %.2f = %.2f\n", num1, num2, ans);
break;
case '/':
if (num2 != 0){
ans = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, ans);
}
else{
printf("Error! Divison by Zero!\n");
}
break;
default:
printf("%c is not a valid operator!\n", choice);
break;
}
}
else if (argc = 3){
sscanf(argv[1], "%c", &choice);
sscanf(argv[2], "%f", &num1);
switch (choice){
case 'n':
case 'N':
ans = -1 * num1;
printf("-(%.2f) = %.2f\n", num1, ans);
break;
case 'a':
case 'A':
ans = sqrt (num1 * num1);
printf("|%.2f| = %.2f\n", num1, ans);
break;
case 's':
case 'S':
if (num1 >= 0){
ans = sqrt(num1);
printf("Sqrt(%.2f) = %.2f\n", num1, ans);
}
else {
printf("Can't find square root of negative number\n");
}
break;
default:
printf("%c is not a valid operator!\n", choice);
break;
}
}
else {
printf("Input Error!!!\n");
}
}