Thread: Using char arrays in branching statements

  1. #1
    Registered User
    Join Date
    Jun 2009
    Posts
    8

    Using char arrays in branching statements

    Evening, very early in the morning (04:45) actually. I'm very new to C, self taught using online tutorials, and I'm trying to create a small, extremely simple program to run equations for me so that I don't have to repeat tediously typing in calculations on my calculator in physics.
    So far, it's all working, runs on a simple directory ( Enter '1' for addition, '2' for subtraction, and so on ) on a branching approach, ( if and else if's ) which works very well until I started inputting all of the equations I have to use, which number in over three dozen. And the directory takes up space.
    Now it's rather confusing. I also got it to work on a single character ( Enter 'a' for addition etc ) but there are only 26 letters, and more equations than that. Not helping much.
    What I was looking for was the ability to type in an array of characters, such as 'addition', which would then be taken by the if statement and then carries out the addition function.

    Code:
        printf("\n\n\n    Choose Operation\n   >: ");
        int operation;
        scanf("%d", &operation);
        if ( operation == 1 )
        {
            float iadd1, iadd2;
            printf("\nOperation: Addition\n\n   First Number: ");
            scanf("%f", &iadd1);
            printf("   Second Number: ");
            scanf("%f", &iadd2);
            printf("\nResult: %f\n\n\n\n", iadd1 + iadd2);
    
        }
    Here's a snippet; as you can see, very simple. What I wanted was to be able to replace the '1' with the word 'addition' and achieve the same effect. Hope that I make sense.

    I've scanned the FAQ, and most of the tutorials, but as I browsed I became increasingly out of my depth. If there isn't a simple solution, then I understand, please say so, and that'll be the end of it.

    And if I sound unbelievably simple and....noobish, then...well, I've only been using C for two days.


    Much appreciate your help, thanks.

    - Harry Manners

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    What you want to do is deal with strings. Make sure you know how arrays work before you proceed. Once you understand both arrays and strings, then look up how to use fgets().

    To get you started with fgets, use stdin as the FILE * in question, and if you want to strip the '\n' char, there are a few common methods floating around.

    After that, look up strcmp() to compare two strings.

    You should be good to go after that.

    Congrats on getting to this point being self-taught, and welcome to cboard.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Ahh, fantastic, thank you very much.

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Perhaps I should have included this in my last post.

  5. #5
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Ah, I see.


    Hmm...I've read up on strings, and I'm understanding how to rid myself of the extra '\n', but I'm not clear on any way to instruct the program to say 'When this word is input, do this, but when this word is input, do that.'

    It may be right in front of me, but I'm finding it awkward to get my head around the problem with nobody to talk to about it. I'd appreciate help with it, but I don't want the work done for me...
    Well at least some of the extra stuff I've done has cleaned up the code, I've put in functions and stuff now, which is neater. But I'm still unsure of this character string if branching. Is it even possible?


    EDIT: Using STRCMP, I've tried to impliment it, but it doesn't appear to be operating, and I get error messages from windows when I compile.
    Here's a snippet:


    Code:
        int variable;
        char a[] = "addition";
        variable = strcmp ( a, buf );
    
             if ( variable == 1 )
      {
    So 'a' is a set character string, and 'buf' is the user input after the \n has been removed. Thoughts?
    Last edited by hmanners; 06-07-2009 at 09:36 AM.

  6. #6
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Ah, fantastic. I have it working now, all good, Thanks so much for your help.


    One more thing. I used goto commands for the [would you like to perform another operation y/n?] prompt, so that the program would loop back to the beginning after the user had finished one function. However, it drops straight through to the else branch (failure) as the 'y' for saying 'yes I want to perform another function' is not a known command for a function. It mistakes the y to loop for an input string for a function.
    And I'm sure by now you're baring your teeth at me for using goto commands ( even the tutorial warned me not to ), but they were the easiest way I could find, and they worked perfectly beforehand, but now they don't.
    I've attempted to use pointers to reset the variables underneath the loop label, shown below.

    Code:
     
        printf("  Calculation Engine\n  Ready...\n\n");
    
     /* Loop Station */
        loop:
    
        char response;
        char buf[BUFSIZ];
        char* buf_reset = "";
        char* response_reset = "";
              buf_reset = &buf;
              response_reset = &response;
    This is to try and intercept the program as it loops, and will immediately reset the variables that are causing it to go straight to the else statement. However, it doesn't work...

    My logic was that the program would pause at fgets for some input for the variable for the buffer (buf), but doesn't, it simple assumes that the variable is blank, and then falls through to the else branch....help?

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You could include everything in an infinite loop:
    Code:
    char response;
    char buf[BUFSIZ];
    while (1) {
          [blah blah]
          if response == 'y' break;
    }
    "break" is the only way out. I put the variable declarations *first* to demonstrate that they do not belong inside the loop (you can reuse them as much as you want after they are declared).

    "goto" is frowned upon as reflective of bad programming technique (which in this case it is!). There is almost always an easier and better way to do something. Some people might even just say always, no almost...
    Last edited by MK27; 06-07-2009 at 01:52 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    A combination of scanf() and fgets() is causing the problem though it's best to post the code snippet to see what's happening.
    If you used scanf() to obtain user input, the newline is left on stdin and the following call to fgets() reads blank due to that.

    Edit: as noted gotos should be avoided at best.
    Last edited by itCbitC; 06-07-2009 at 01:52 PM.

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by MK27 View Post
    "break" is the only way out.
    Except it's not...
    Quote Originally Posted by MK27 View Post
    "goto" is frowned upon as reflective of bad programming technique (which in this case it is!). There is almost always an easier and better way to do something. Some people might even just say always, no almost...
    Which still doesn't make "break" "the only way out".


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Code:
     printf("\n\n\nWould you like to perform another operation? (Y/N): ");
    
    
            /* Repetition Station */
    rep:
    
    
            scanf("%c", &response );
            if ( response == 'y' || response == 'Y' )
            {
                goto loop;
            }
            else if ( response == 'n' || response == 'N' )
            {
                goto end;
            }
            else {
                goto rep;
            }
    
    
            /* End Program Station */
    
        end:
        printf(" \n\n\n   >: End Program\n\n\n");
    That's the very bottom of the program, where the goto commands are. And yes, I used scanf().
    When yes is input, the goto loop; command makes the program jump near to the top of the program, shown below [label loop:]

    Code:
    int main()
    {
         /* Loop Station */
        loop:
        printf("  Calculation Engine\n  Ready...\n\n");
    
    
        char response;
        char buf[BUFSIZ];
        char* buf_reset = "";
        char* response_reset = "";

    I'm sure I'm making it difficult for myself by using the goto commands, but I'm struggling to grapple with other methods of looping...Is there a way to get the goto commands to work in this situation? Or should I abandon it?

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by quzah View Post
    Which still doesn't make "break" "the only way out".
    Yes, you could exit the program, call a function that exits the program, return from the function containing the loop, etc. but hopefully the point about the meaning of "break" was made.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by hmanners View Post
    Or should I abandon it?
    That depends. If you just want to finish this up ASAP so you can use it, that's one thing. If you are also trying to learn C and think you might be writing more in the future, then definitely forget goto and concentrate on implementing loops. They are fundamental -- ie, you won't get far without them. Where did you pick up this idea to use "goto" for all this?

    I'm a little confused:

    Quote Originally Posted by hmanners View Post
    When yes is input, the goto loop; command makes the program jump near to the top of the program,
    Isn't that what you intended? Or do you mean, that is what you intended, but that is not what happens?

    Here's an example of how you might use loops and functions in a C program to control the flow of execution:
    Code:
    int get_response () {
          char r;
          printf("Would you like to perform another operation? (Y/N): ");
          scanf("%c%*c", &r);
          if (r=='y') return 1;
          else if (r=='n') return 0;  
          else return get_response();
    }
    
    int main() {
          while (1) {
                 [ ...all the important stuff here... ]
                 if (!(get_response())) break;
          }
          return 0;
    }
    Do you see how the "get_response" function covers this (from your post):
    Code:
            if ( response == 'y' || response == 'Y' )
            {
                goto loop;
            }
            else if ( response == 'n' || response == 'N' )
            {
                goto end;
            }
            else {
                goto rep;
            }
    get_response() returns 1 ("true") or 0 ("false"). "if (!(get_response)) break;" means if get_response does not return true, break out of the loop. Notice the condition of the loop is just (1), which is always true.

    The red bit in the scanf line is important. When you type "y" you also hit return, meaning there are *two* characters submitted, 'y' and '\n'. %c only takes the first one, so the \n will come back again the next time you ask for input. The asterisk in %*c tells scanf to read in one more character, but discard it instead of placing it into a variable. There is a flaw in this in that if the user wants answers "certainly!", get_response will chew thru the line, checking every odd numbered character:
    c (e)
    r (t)
    a (i)
    n (l) <-- found an 'n'!
    y (!)
    Last edited by MK27; 06-07-2009 at 04:09 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    IMO avoid the gotos as much as you can.
    You can use a switch statement inside an infinite while loop as MK27 stated.

  14. #14
    Registered User
    Join Date
    Jun 2009
    Posts
    8
    Ahh, okay thanks guys. Goto commands gone. I've implemented the while loop, works great, but only for the if branch 'directory', which prints the command inputs for the different functions. But when I actually type in the input for a function, it carries it out, asks if I want to carry out another operation, and then simply repeats asking me this, whatever I input (y, n, or any other input ).
    It's very strange...I'm not sure why it would do this, other than the clue that the functions have input from the user, whereas directory does not...


    EDIT: I've found that by removing any user input from any of the 'if' branches, the loop works. As soon as there is input, the loop doesn't work, and simply repeats asking whether repeated operations are required...
    Last edited by hmanners; 06-07-2009 at 05:53 PM. Reason: Discovery

  15. #15
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    so post what you have implemented so far

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  3. I'm having a problem with data files.
    By OmniMirror in forum C Programming
    Replies: 4
    Last Post: 05-14-2003, 09:40 PM
  4. Strings are V important...
    By NANO in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2002, 11:57 AM