Thread: Confused about syntax...

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    2

    Question Confused about syntax...

    Hello, I am new to learning c programming, and I am trying to understand where my concept went wrong in this code:

    Code:
    /* The idea of this program is to simply ask the user to input a yes or no
    which if yes would respond with printf("You have entered into the castle.");
    and if no: would not give a response, but would wait for the user to press
    any key to close the program. */
    
    #include <stdio.h>
    #include <conio.h>
    
    /* I am not sure of needing conio.h here - as it isn't really math? */
    
    int main(void) /* does void simply mean close the program once done running int main? */
    {
    	int yes;
    	int no;
    	int ansr;
    	printf("You are at the entrance of a castle.\nDo you wish to enter?\nYes or No:\n");
    	scanf("yes", &yes "no", &no); /* syntax error before string constant? */
    
    	ansr("yes", &yes + "no", &no);
    
    	if ansr = yes then printf("You have entered into the castle.");
    
    	getch();
    	}
    
    /* I based the code on a simple 'add two numbers' source tutorial for begining c programming.
    Obviously, the issues aren't adding numbers here, but I hoped that scanning for a yes or no answer
    and setting the answer to the int yes or int no would allow ansr to be the value of yes and no combined,
    which when one has no value and the other does would then make the answer one or the other and then
    I hoped that the 'if ansr = yes then' statement would respond with the printf 'entered castle' bit. */

    Any knowledge given is greatly appriciated. Once I get the feel for correctly arranging the code - I will spend much more time in studying the specifics. If I could get a few tips on better arranging this kind of thing, I will gladly dig into working out something more suitable to learn more from. Thanks ~ Justin

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Obviously, the issues aren't adding numbers here, but I hoped that scanning for a yes or no answer
    and setting the answer to the int yes or int no would allow ansr to be the value of yes and no combined,
    which when one has no value and the other does would then make the answer one or the other and then
    I hoped that the 'if ansr = yes then' statement would respond with the printf 'entered castle' bit.
    I think it would be wise to forget about what you've heard. You can revisit this program when you have a better understanding of whatever that method may really be.

    If you want to make the user pick a binary choice, (in this case between entering the castle or not) you need to understand if statements. An if statement will branch to one section of code if a Boolean condition is true, or another section if it is false. So depending on the logic, entering the castle will go in one section and not entering in the other.

    In code it looks like this:

    Code:
    if ( condition ) 
    {
       /* do this if true */
    }
    else
    {
       /* or this if false */
    }
    That is the simplest of choices. If statements can be made necessarily more complicated with else if, but you'll probably learn that soon.

    So the hard part is filling in your details. You mostly figured it out, but that is what needs fixing. There are many ways to do this, but I figure I'd so you an arguably more difficult one and then maybe you would learn to fix what you have.
    Code:
    #include <stdio.h>
    #include <string.h>
    int main(void) /* The void here means no arguments to main, which also applies in other functions */
    {
       char enterCastle[16] = ""; /* Choose a variable to represent the answer */
       int i;
       printf("You are at the entrance of a castle.\nDo you wish to enter?\nYes or No:\n");
       for (i = 0; i < 15; ) {
          if (scanf("%c", &enterCastle[i]) == 1) {
              if (enterCastle[i] == '\n') {
                  break;
              }
              else {
                  ++i;
              }
          }
          else {
              printf("Input Error: Whatever you typed was not a character.\n");
              return 0;
          }
       }
       enterCastle[i] = '\0'; /* throw away that \n we read */
    
       /* This is the important part: */
       if (strcmp(enterCastle, "Yes") == 0) {
          printf("You have entered the castle.\n");
       }
       else {
          printf("You were eaten by a grue.\n");
       }
       getchar();
       return 0;
    }
    So there would be your program. Some things may be new but nothing impossible to look up. This reads a character at a time to put into a string, which should give you an idea what to do with scanf(). Also, rather than use getch() I used getchar() because it's standard.

    Also, checking scanf()'s return value is not necessarily important here, but I think new people need to embrace it as fast as they can. The return value is the only useful way of knowing that your input is working.

    It may be late but merry christmas!
    Last edited by whiteflags; 12-25-2010 at 11:39 PM.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Whiteflags has given you some excellent advice, although it may be just a tad complex for someone working on one of their very first programs...

    Code:
    int main(void) /* does void simply mean close the program once done running int main? */
    {
    	int yes;
    	int no;
    	int ansr;
    	printf("You are at the entrance of a castle.\nDo you wish to enter?\nYes or No:\n");
    	scanf("yes", &yes "no", &no); /* syntax error before string constant? */
    
    	ansr("yes", &yes + "no", &no);
    
    	if ansr = yes then printf("You have entered into the castle.");
    
    	getch();
    	}
    The void in int main (void) indicates that you are not going to process command line arguments in your program. When you see that in a procedure definition it means no variables are passed into the function.

    First of all you can't just make stuff up... C is a serious idiot. You have to speak it's language EXACTLY or it's going to get all confused on you. It has a very short list of "keywords" it understands (if else while for etc.) the rest is going to cause it problems. Lines like...
    Code:
    scanf("yes", &yes "no", &no); 
    ansr("yes", &yes + "no", &no);
    ... no matter what you want it to do are just going to cause a "syntax error", the compiler's way of saying "I don't understand".

    So... lesson 1, learn to speak C... 'cause it ain't never gonna learn your language.

    Now, lets take a look at the intent of your program... What do you want to do?

    You say you're looking for a simple decision from your operator... Yes or No... in response to a simple question printed on screen.

    Ok... that's pretty easy. In general you can assume that Y or y mean Yes and *everything else* means No. The reason I generally suggest that is that some operators are very dumb, very few actually read the screen, so if they're hammering around on the keyboard, you want your program to abort rather than causing system errors.

    So we can safely say that unless the operator types a Y or a y (and they are two different things in C) you want your program to exit.

    The first thing to figure out is how to print the message... The C library has a nifty function puts() that prints strings on the screen... Very handy. (Look it up!)
    Code:
     
    #include <sdtlib.h>
    #include <stdio.h>
    
    int main(void)
      {
    
        // print message on screen...
        puts("Do you want to enter THE CASTLE : y/n :");
    
        return 0;
    }
    So... compile what you've got so far and see what it does...

    Now... How do we get that Y or y from the keyboard? The C library has a standard function called getchar() which reads a single keystroke then carries on... perfect for what you want. (Look it up!)
    Code:
     
    #include <sdtlib.h>
    #include <stdio.h>
    
    int main(void)
      {
    
         int ans;  // for user response
    
        // print message on screen...
        puts("Do you want to enter THE CASTLE : y/n :");
      
        // get user response from keyboard
        ans = getchar();
    
        return 0;
    }
    Compile again and see how this works....

    Now we need to decide what to do with that answer...
    You've said that if they answer Yes (Y or y) you want to print a message. Anything else should cause a program exit. The logical way to think about this is "if they type anything but a Y or a y, the program ends"... Now to code this we use an "if" statement, similar to the one Whiteflags showed you. (You should look this up too!)

    To do this we have to test the value from the keyboard stored in the ans variable. We have a very limited group of choices == (equals) != (not equal) etc. In this case it's the != we're interested in. Further we have two possibilities Y and y so we have to test both. The && operator says "and"... so we get the new line below...

    Code:
     
    #include <sdtlib.h>
    #include <stdio.h>
    
    int main(void)
      {
    
         int ans;  // for user response
    
        // print message on screen...
        puts("Do you want to enter THE CASTLE : y/n :");
      
        // get user response from keyboard
        ans = getchar();
    
        // exit unless Y or y entered.
        if ((ans != 'Y') && (ans != 'y'))
          exit(0);
    
        // the only way to get here is with a Yes answer so print the message
        puts("You have just entered The Castle!... Welcome");
    
        return 0;
    }
    I think this is about the simplest form of this task possible...

    This is the general flow of things when developing programs... think in little tiny blobs... always speak the compiler's language... build in bits and pieces. As you gain more experience your blobs will get a bit bigger and things will get easier.
    Last edited by CommonTater; 12-26-2010 at 01:33 AM.

  4. #4
    Registered User
    Join Date
    Dec 2010
    Posts
    31

    see if this is helpful

    I have not used scanf in the past so wanted to give it a try.
    Here is what I have come up with, albeit there are many ways
    to do this and there is some room for improvement, but I did
    not want to over-complicate the code.

    Code:
    
    #include <stdio.h>
    #include <strings.h>
    
    int
    main(void)
    {
    
            char yes[] = {"yes"};
            char no[] = {"no"};
            char answer[10] = {""};
    
    
            printf("Do you wish to enter the castle. Please enter yes or no: ");
            scanf("%s", answer);
    
            if (strcmp(answer, yes) == 0) {
                    printf("Entering the castle\n");
            }
            else if (strcmp(answer, no) == 0) {
                    printf ("Not entering the castle\n");
            }
            else {
                    printf("you have not entered yes or no\n");
                    printf("your answer was %s\n", answer);
            }
    
            return 0;
    }

  5. #5
    Registered User inequity's Avatar
    Join Date
    Nov 2010
    Location
    Seattle, Washington
    Posts
    59
    Quote Originally Posted by kona49er View Post
    I have not used scanf in the past so wanted to give it a try.
    Here is what I have come up with, albeit there are many ways
    to do this and there is some room for improvement, but I did
    not want to over-complicate the code.

    Code:
    
    #include <stdio.h>
    #include <strings.h>
    
    int
    main(void)
    {
    
            char yes[] = {"yes"};
            char no[] = {"no"};
            char answer[10] = {""};
    
    
            printf("Do you wish to enter the castle. Please enter yes or no: ");
            scanf("%s", answer);
    
            if (strcmp(answer, yes) == 0) {
                    printf("Entering the castle\n");
            }
            else if (strcmp(answer, no) == 0) {
                    printf ("Not entering the castle\n");
            }
            else {
                    printf("you have not entered yes or no\n");
                    printf("your answer was %s\n", answer);
            }
    
            return 0;
    }
    Now I'm probably not as experienced as the guys who posted advice for you before, but I had one question for you. Is there any reason that you're declaring the 'yes' and 'no' as their own variables?

    Because both of your strings are null-terminated, strcmp() should be working properly, but it still seems a bit unnecessary. Aside from that, I haven't much to add to what's already been said.

  6. #6
    Registered User
    Join Date
    Sep 2008
    Posts
    58
    Writing code like that is like adding when you should be multiplying.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by blurx View Post
    Writing code like that is like adding when you should be multiplying.
    Do you know the best part about making clever statements? Actually being clever. Try it sometime.


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

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by kona49er View Post
    I have not used scanf in the past so wanted to give it a try.
    Here is what I have come up with, albeit there are many ways
    to do this and there is some room for improvement, but I did
    not want to over-complicate the code.

    Code:
    
    #include <stdio.h>
    #include <strings.h>
    
    int
    main(void)
    {
    
            char yes[] = {"yes"};
            char no[] = {"no"};
            char answer[10] = {""};
    
    
            printf("Do you wish to enter the castle. Please enter yes or no: ");
            scanf("%s", answer);
    
            if (strcmp(answer, yes) == 0) {
                    printf("Entering the castle\n");
            }
            else if (strcmp(answer, no) == 0) {
                    printf ("Not entering the castle\n");
            }
            else {
                    printf("you have not entered yes or no\n");
                    printf("your answer was %s\n", answer);
            }
    
            return 0;
    }
    The problem doing this with strings is that you are dealing in many permutations...

    The simple Y or y test now requires you to test for "yes" "YES" "Yes" yEs" "yeS" "YEs" and "no" "NO" "No" "nO"

    Count your lucky stars you weren't testing for "antidisestablishmetarianism".

    Some C versions have a library function _stricmp() which deal with this, but it is not standard C-99.

    Also I'm a little puzzled about why you need a yes and no variable when you could have simply done this...
    Code:
    if (!strcmp(answer,"yes"))
     ....
    Last edited by CommonTater; 12-27-2010 at 03:51 PM.

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well if you don't have case insensitive comparison function, you have an excuse to write one.
    Last edited by whiteflags; 12-27-2010 at 05:48 PM.

  10. #10
    Registered User inequity's Avatar
    Join Date
    Nov 2010
    Location
    Seattle, Washington
    Posts
    59
    It seems like the easiest way would be to scan for a character, and check if it is 'Y', 'y', 'N', or 'n'.

    However, it looks like you're trying to write a pretty big game. If that's the case, I would suggest taking some time and learning a bit more about this stuff. You probably shouldn't be using string functions if you're having trouble setting up if statements and using basic IO functions.

    And, as said above, a great way to learn about this stuff would be to try and write some of these functions yourself.

  11. #11
    Registered User
    Join Date
    Dec 2010
    Posts
    31
    Quote Originally Posted by CommonTater View Post
    The problem doing this with strings is that you are dealing in many permutations...

    The simple Y or y test now requires you to test for "yes" "YES" "Yes" yEs" "yeS" "YEs" and "no" "NO" "No" "nO"

    Count your lucky stars you weren't testing for "antidisestablishmetarianism".

    Some C versions have a library function _stricmp() which deal with this, but it is not standard C-99.

    Also I'm a little puzzled about why you need a yes and no variable when you could have simply done this...
    Code:
    if (!strcmp(answer,"yes"))
     ....
    As I mentioned in my original post, there is room for improvement. Here is one that
    addresses your concern about "many permutations".

    Code:
         if (strcasecmp(answer, yes) == 0) ...

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I am new to learning c programming
    Code:
    if ansr = yes then
    Let me guess; Your previous languages experience is with Pascal or Delphi?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 14
    Last Post: 07-14-2009, 08:16 AM
  2. An error is driving me nuts!
    By ulillillia in forum C Programming
    Replies: 5
    Last Post: 04-04-2009, 09:15 PM
  3. Includes making me insane >.<
    By IceDane in forum C Programming
    Replies: 14
    Last Post: 04-14-2008, 10:24 AM
  4. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  5. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM