John D'Amore
John D'Amore

Reputation: 11

Printing out an error message in terminal

I am working on a program that determines the mode of a set of values for example (3 4 2 3 3) should print out "3". The catch is the program must receive the option of the mathematical function to execute and its arguments as parameters in the main function so no user input. Everything must be inserted in the command line and check by using pointers. My program works except for example say the user enters (mode) but doesn't enter in any values after. This should then print a message that just says "ERROR" and the program ends. However it does not instead it prints

Johns-MacBook-Pro-2:AdvanceCalc jvdamore$ ./a.out mode Segmentation fault: 11

when it should print

Johns-MacBook-Pro-2:AdvanceCalc jvdamore$ ./a.out mode ERROR

below is my code. So my question is does my if statement with strcmp(p[2], "") == 0 work in order to produce the desired error message? or am I doing something wrong?

int main(int n, char **p)
{
int i, x, A[100];


if (strcmp(p[1], "mode")==0){

    if (strcmp(p[2], "") == 0){
        printf("ERROR");
    return -1;
}
        for(i=2;i<n;i++){

                if (sscanf(p[i], "%d", &x) != 1) {
                        printf("ERROR");
                        return -1;
                    }
                if (x<1 || x>30){
                        printf("ERROR");
                        return-2;
                    }

                A[i-2]= x;

            }
            find_mode(A, n-2);

        }

Upvotes: 0

Views: 1151

Answers (1)

William Pursell
William Pursell

Reputation: 212198

Rather than comparing a string to "" with strcmp, you need to see if it is NULL. strcmp( NULL, "" ) does not work very well, and you should instead do:

if( p[2] == NULL ) 

(well, really, you should rename the varaible argv, and there are several other issues, but this is the main problem. Make sure you have checked that p[1] is not NULL before you reference p[2])

Upvotes: 2

Related Questions