Resolved Beginner C help

Discussion in 'Mac Programming' started by Watabou, Feb 15, 2011.

  1. Watabou, Feb 15, 2011
    Last edited: Feb 16, 2011

    Watabou macrumors 68040

    Watabou

    Joined:
    Feb 10, 2008
    Location:
    United States
    #1
    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? :(
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    Tip: google "strcmp" and study what its return value is.

    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.
     
  3. Watabou, Feb 15, 2011
    Last edited: Feb 16, 2011

    Watabou thread starter macrumors 68040

    Watabou

    Joined:
    Feb 10, 2008
    Location:
    United States
    #3
    Aww, it was so easy. I can't believe I spent 2 hours on that.

    Thanks kainjow. It works wonderfully now!
     
  4. flashy-cat macrumors regular

    flashy-cat

    Joined:
    Apr 8, 2007
    Location:
    UK
    #4
    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.
     

Share This Page