CBunny
CBunny

Reputation: 23

C Program not Comparing chars correctly

I am working on this C code and I am confused why this is not working. I have looked at other questions here for comparing 2 chars and I have done it the exact same way but for some reason it isn't working.

What happens when it runs is that it will work for t and o, but not for c, even though I have implemented them all the same way.

Split_string was provided to us (no bugs) and returns the number of words in the string inputted via the keyboard. It also takes in an array of strings and puts each word at a different index.

Any suggestions would be greatly appreciated

    char input[100];
    printf("What commmand would you like to use? t, o, or c\n");
    while(fgets(input, 100, stdin)!=NULL){
            char ** ptr  = malloc(sizeof(char*)*10);
            int wordno = split_string(input, ptr);


            if((*ptr[0]=='t') && wordno==1) {
                    text(root_ptr);
            } else if(*ptr[0]=='t' && wordno>1){
                    printf("No arguments for function t\n");
            } else if(*ptr[0]='o' && wordno==9){
                    open(root_ptr);
            } else if(*ptr[0]=='o' && wordno != 9){
                    printf("Need 8 attributes to open o\n");
            } else if(*ptr[0]=='c' && wordno==2){
                    open(root_ptr);
            } else if(*ptr[0]=='c' && wordno !=2){
                    printf("Only need 2 arguments to copy\n");
            } else {
                  printf("Please enter a value command\n");
            }
             printf("Enter t to text, o to open or c to copy\n");

    }

Upvotes: 1

Views: 108

Answers (2)

LSerni
LSerni

Reputation: 57378

The error is here:

else if(*ptr[0]='o' && wordno==9){

where you force the first character to be 'o'. For that reason I usually write comparisons in the Yoda form:

if (('o' == (*ptr[0])) ...

even if it at first it looked awkward and is overkill. If an equal sign you forget, an error the compiler will throw.

However, this kind of behaviour should have been caught by activating the full warnings on the compiler. I strongly suggest you to keep them on at all times.

Also, you allocate the memory again at each cycle, causing a leak (this won't bite you very soon, if at all, but still):

char ** ptr  = malloc(sizeof(char*)*10);

Finally, you might be better served by a switch statement:

switch(*ptr[0]) {
    case 't':
        ...
        break;
    ...
    default:
        printf("Huh?\n");
        break;
}

Upvotes: 2

koalo
koalo

Reputation: 2313

Check the following line. There is a = missing, so you actually assign o to the first element of your array instead of comparing with o. Afterward, it can never be c.

} else if(*ptr[0]='o' && wordno==9){

Upvotes: 6

Related Questions