Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Watabou

macrumors 68040
Original poster
Feb 10, 2008
3,426
759
United States
Hi guys,

I have to write a program for uni. It's a beginner C class and we have to write a simple dumb program.

One of the feature of the dumb program is when the user enters "toggle" into the command line, the program says "off" and when you put toggle again, the program outputs "on".

I've been at this for over two hours now and I think I may have gotten the syntax wrong.

Here's part of my code:

Code:
while (keep_going = 1) {
        
        printf("Enter command: ");
        fgets(command, sizeof(command), stdin);
        command[strlen(command)-1] = '\0';
        
        if(strcmp(command, "toggle")) {
            if(toggle == "on") {
                strcpy(toggle, "off");
                printf("Toggle is now %c\n", toggle);
            }
            else if(toggle == "off") {
                strcpy(toggle, "on");
                printf("Toggle is now %c\n", toggle);
            }
        }
        else
            printf("Command unrecognized.\n");

Whenever I enter toggle into the command prompt, it outputs "command not recognized so it's skipping over the if statements for some reason. C isn't like Java, which I'm pretty used to so I'm really confused as to why this is happening.

Oh and just for reference, I have these two variables:
char toggle[4] and char command[100]

Help please? :(
 
Last edited:
Whenever I enter toggle into the command prompt, it outputs "command not recognized so it's skipping over the if statements for some reason.
Tip: google "strcmp" and study what its return value is.

C isn't like Java, which I'm pretty used to so I'm really confused as to why this is happening.
Java is like living in a mansion while C is like living in a cardboard box ;)

One more thing: you started with the right idea using strcmp for comparing strings but then used ==. You cannot use == in C to compare the contents of two strings. == is instead comparing the values of the pointers. So look again at what strcmp does and what it returns.
 
Aww, it was so easy. I can't believe I spent 2 hours on that.

Thanks kainjow. It works wonderfully now!
 
Last edited:
Unless you want the while statement to loop forever, you need to change the while condition to

Code:
while (keep_going =[COLOR="Red"]=[/COLOR] 1) {

The compiler should've given you a warning along the lines of "possible unintended assignment" etc.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.