Thread: Guess What...??

  1. #1
    Registered User
    Join Date
    Apr 2011
    Location
    Karachi, Pakistan
    Posts
    19

    Guess What...??

    Hello there...!!

    I am using a Borland Turbo C 3.0 compiler. I made a quiz programme that asks a GK question. The user is asked a question and given three chances to answer it correctly. For a correct first guess, you score 4 points. For a correct second guess, you score 2 points and for a correct third guess you score 1 point. No point is scored after third chance and the 'default' statement is executed which dispays the correct answer. Here is the programme:
    GUESS.txt
    The problem is that my programme bypasses all the 'switch/cases' and other 'if else' statements and directly jumps to the 'default' statement. I mean even if you type in the correct guess the first time, it always displays the default answer and awards no point.

    Please help me with this. Also I wanted to ask whether 'scanf' takes up 'a string' as input or not and process it for operations such as printing, comparing the input against a value and like purposes......????

    Thanks
    Attached Files Attached Files

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok... lots of issues here...

    1) Borland's TurboC compiler has been abandoned for nearly 25 years. It outputs 16 bit code which won't even run on 64bit operating systems. Unless you are using a very very old computer, there are lots of better choices you can make.

    2) Please don't post links to code... use the forum's built in code tags and post the code here where people can see it. To avoid getting their systems "virused" many people will not follow your links...

    3) having looked at your code, the problem is pretty simple. C (even the modern flavours) is totally unable to make string comparisons across the == sign or any other. You need to use string library functions such as strcmp() or write a character by character comparison procedure of your own.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Location
    Las Vegas
    Posts
    66
    Your "guess" array is an array of char, into which you're storing an integer value 0 or 1 at element 15. You then attempt to use a switch statement on the characters '0' or '1' (which have ASCII integer values of 48 or 49, respectively). You will always fall through to your default case in this situation.

    It seems as though you started on one design path, and ended up doing something else. I think you are wanting to use a C string, in which case CommonTater's remarks are right on - you'll need to use the strcmp() function to compare strings. However, in your implementation, you are using a single element of the char array "guess" and comparing it to a char variable "JAPAN", which is perfectly legitimate. What is your intent? (Hint: Comments really help!)

    Another problem is that you have commented out the definition of the integer variable "score". Therefore, the compiler sees subsequent references to "score" as an undeclared identifier: it can't proceed.

    I'm curious why you chose to create an autonomous block of code, starting from before the scanf() statement and extending to the getch() statement near the end of the program (i.e. an extra set of curly braces). In this particular instance, there are no specific ramifications from doing so, however, had you defined any variables within this block, they would have been local to this block - a side effect you might not have been wanting. If this is intentional, I highly recommend you leave a comment as to why you're doing it. If it is unintentional, I would suggest you remove this code block.

    I'm uncertain about Turbo C, but modern C requires that the main function be defined to return an int (rather than void). Accordingly, your main function should actually return an int.

    LOL Where'd you even find a copy of Turbo C? It's practically a collector's item these days!

    Kevin

  4. #4
    Registered User
    Join Date
    Apr 2011
    Location
    Las Vegas
    Posts
    66
    Oops, sorry, missed your second question... scanf will read all non-whitespace characters and store them into a C string whose address you've passed as an argument. I'm thinking that instead of
    Code:
    scanf("%s",&guess[15]);
    what you really mean to say is
    Code:
    scanf("%s", guess);
    Note that because the way C passes arrays as arguments, they are always passed by reference (rather than by value), so it is not necessary to use the & operator when passing the entire array.

    scanf will properly terminate the input with the required null character ('\0'), so you can then use "guess" as a C string with any function that expects a C string (e.g. puts(guess); ).

    It's important to remember that C does not protect you from yourself (or your users). You are responsible for ensuring that the variable into which you're reading these characters is of sufficient size to hold them all!

    Hope that helps-
    Kevin

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Borland Turbo C 3.0
    Seriously?!
    Does that come on like 3.5 inch floppy disks or perhaps 5.25 inch...?
    Are you running like Windows 95 as well or something?
    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"

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by iMalc View Post
    Seriously?!
    Does that come on like 3.5 inch floppy disks or perhaps 5.25 inch...?
    Are you running like Windows 95 as well or something?
    I may be mistaken but I believe there was even a version of TurboC available on 8" disks...
    My first version of Pascal was on 3 5.25 inchers.

  7. #7
    Registered User
    Join Date
    Apr 2011
    Location
    Karachi, Pakistan
    Posts
    19
    Lord Slytherin@ CommonTater
    Lord Slytherin@ imalc
    Dears...

    I know that my poor Borland's Turbo C compiler has been abondoned fairly long time ago, however it still offers easy learning opportuinities to the beginners seeing that it was developed at the incipient stage of computer prgramming. As to the code capacity, there are 5 memory models (small,compact,medium,large and huge) which u could choose according to your scope, and by the way all of them accept code upto at least 64K and data storage of the same 64K limit.

    Thanx to your advice regarding posting code within the code tags. I'll try to do likewise next time.

    And u see I'm a beginner so I dont know how exactly to insert the 'strcmp()' function into my programme though it seems good to do because character by charcter comparison is something I had already thought of and rejected it instantly considering the length of the programme. Could anyone of you please write me the code lines for that....???

    And for your kind awareness, I'm using Windows XP service pack 3.0 which has DOS command line interpreter as a built in application. So where there's DOS, there is HOPE still for oldies. You know Borland Turbo C 3.0 is a free ware available on
    http://http://www.brothersoft.com/windows/development/

    Good day to you both....!!

    Slytherin

    Help shall always be given to those at hogwarts who ask for it...!
    ALBUS DUMBLEDORE

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Lord Slytherin View Post
    I know that my poor Borland's Turbo C compiler has been abondoned fairly long time ago, however it still offers easy learning opportuinities to the beginners seeing that it was developed at the incipient stage of computer prgramming. As to the code capacity, there are 5 memory models (small,compact,medium,large and huge) which u could choose according to your scope, and by the way all of them accept code upto at least 64K and data storage of the same 64K limit.
    Not the incipient stage. Version 3 was developed in 1991. Computer programming has been around since, well, the first computers in the 1940's (Z3). Any memory model used to save space should probably be restricted to embedded systems. And 64K is nothing to brag about, even if it fits Hello World with enough room for a followup quote from Harry Potter. But you do need something less than 20 years old. The C language has changed a great deal, and continues to change. Learn with good tools (there are many free ones) that will give your current, relevant skills, so you don't have to unlearn all the bad habits that Turbo C allows/encourages. And yes, it allows and encourages bad habits (like void main). The rules were looser back then, and fewer people were concerned with writing good, portable, standards-compliant C programs.

    Thanx to your advice regarding posting code within the code tags. I'll try to do likewise next time.
    Good. We look forward to helping you learn C.

    And u see I'm a beginner so I dont know how exactly to insert the 'strcmp()' function into my programme though it seems good to do because character by charcter comparison is something I had already thought of and rejected it instantly considering the length of the programme. Could anyone of you please write me the code lines for that....???
    How familiar are you with functions? Perhaps a brief tutorial would help? Read up a bit in books too, and Google around. The general idea is strcmp(string1, string2). If that returns 0, they match, otherwise, they don't. Google for more details of strcmp.

    And for your kind awareness, I'm using Windows XP service pack 3.0 which has DOS command line interpreter as a built in application. So where there's DOS, there is HOPE still for oldies. You know Borland Turbo C 3.0 is a free ware available on
    http://http://www.brothersoft.com/windows/development/
    Hate to break it to you, but it's not real DOS. It's faked/emulated. You're also using a 7 or 8 year old OS. The new ones are stopping support for 16-bit programs (read: Turbo C) all together. You should really try to keep up. And we're aware that Turbo C is free, but we wish it weren't. We wish it would go away and die, so people would stop using it and propagating bad habits. There are better free alternatives, like Pelles C or Code::Blocks with MinGW.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by anduril462 View Post
    There are better free alternatives, like Pelles C or Code::Blocks with MinGW.
    Just a minor correction: Code::Blocks is not a compiler. It is an IDE that can make use of other compilers on your system. It can be downloaded in a bundle with a version (usually not the latest, but usually a fairly recent one) of MingW.

    If you want a slightly more extensive list of free C/C++ compilers and interpreters - of varying quality - have a look here. It lists Turbo C 2.01 though
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Registered User
    Join Date
    Apr 2011
    Location
    Karachi, Pakistan
    Posts
    19
    Dear Kmess...!

    Your indication to my wrong use of '0' and '1' as switch-cases has been of some help to me. You see I've changed the case values with 'a' and 'b' instead of '1' and '0'. Its effect is that my programme doesn't directly jump to the default statement now but all the same, even if the user answers correctly, it ignores the case'a' and always goes to case 'b' and executes the code within that:
    Code:
         case'b':
    	     printf("Wrong Answer\nTry again\n");
    		scanf("%s",&guess[15]);
    		if(guess[15]==JAPAN)
    		  printf("Correct\nYour score is %d.",score+2);
    		else
    		  {printf("Wrong again\nTry once more");
    		     scanf("%s",&guess[15]);
    		      if(guess[15]==JAPAN)
    		      printf("right this time\nscore=%d",score+1);}
    		      break;
    	 default:
    	     printf("SORRY You LOST!\nyour score is %d.",score);
    Kmess please dont misunderstand me. Though I'm a beginner but not an ill-organised person. This programme has been pre-thought. I've an Algorithm for it. I have a flowchart too which I could send to you if you like. Feel free to ask. In my programme, I've used 'The Conditional operator' for the decision-making step, which is the only ternary operator in Turbo C
    Code:
        guess[15] = (guess[15]==JAPAN) ? 'a' : 'b';   /*conditional operator*/
    Its purpose is to test the condition in the parentheses (in this case "guess[15]==JAPAN"). If found true, it allots the value preceding the colon ('a' in this case) to the variable operand (guess[15]); and vice versa.

    In my prog. the conditional operator always allots the value 'b' to the variable. This is what has now become the problem.I added a 'printf' statement right after the conditional operator to check out its value. like this
    Code:
       
                 scanf("%s",&guess[15]);
                 guess[15] = (guess[15]==JAPAN) ? 'a' : 'b';   /*conditional operator*/
                 printf("%c",guess[15]);
    and it always prints value 'b' even when the user answers correctly, which confirms the error.

    PHP Code:
    Another problem is that you have commented out the definition of the integer variable "score"Thereforethe compiler sees subsequent references to "score" as an undeclared identifierit can't proceed. 
    No use even after removing the comments. Infact the compiler did initialize 'score' before as good as it does now after removing comments.

    PHP Code:
    I'm curious why you chose to create an autonomous block of code, starting from before the scanf() statement and extending to the getch() statement near the end of the program (i.e. an extra set of curly braces). 
    Yes, let me explain. Actually I would be adding more questions to this prog. So I wanted to separate different Q's coding into different blocks. I now see where the first brace should have been. Like

    Code:
    void main()
    {
     char guess[15],JAPAN='q';
     int score=0;
     clrscr();
     printf("\"WELCOME\"\nPlease turn on your Caps Lock.\n");
     {
       printf("Which country is called \"The Land of The Risisng Sun\" ?\n");
         scanf("%s",&guess[15]);
         guess[15] = (guess[15]==JAPAN) ? 'a' : 'b';   /*conditional operator*/
         switch ( guess[15] )
    	{
    	 case'a':
    	     printf("That's corrrrrrect\n");
    	     printf("Your score is %d.",score+4);
    	     break;
    	 case'b':
    	     printf("Wrong Answer\nTry again\n");
    		scanf("%s",&guess[15]);
    		if(guess[15]==JAPAN)
    		  printf("Correct\nYour score is %d.",score+2);
    		else
    		  {printf("Wrong again\nTry once more");
    		     scanf("%s",&guess[15]);
    		      if(guess[15]==JAPAN)
    		      printf("right this time\nscore=%d",score+1);}
    		      break;
    	 default:
    	     printf("SORRY You LOST!\nyour score is %d.",score);
    	}
      }
     getch();
    }
    And as to your concern regarding the function definition using "void main()", it is the default criterion of function definition in Turbo C.

    I also request you to help me writing the code lines for strcmp() and tell me the prototype used for it.

    Thanks.

    Slytherin

    Help shall always be given to those at Hogwarts who ask for it...!
    Albus Dumbledore

  11. #11
    Registered User
    Join Date
    Jun 2010
    Location
    Michigan, USA
    Posts
    143
    Quote Originally Posted by Lord Slytherin View Post
    <snip>
    Code:
    void main()
    {
     char guess[15],JAPAN='q';
     int score=0;
     clrscr();
     printf("\"WELCOME\"\nPlease turn on your Caps Lock.\n");
     {
       printf("Which country is called \"The Land of The Risisng Sun\" ?\n");
         scanf("%s",&guess[15]);
         guess[15] = (guess[15]==JAPAN) ? 'a' : 'b';   /*conditional operator*/
         switch ( guess[15] )
    	{
    	 case'a':
    	     printf("That's corrrrrrect\n");
    	     printf("Your score is %d.",score+4);
    	     break;
    	 case'b':
    	     printf("Wrong Answer\nTry again\n");
    		scanf("%s",&guess[15]);
    		if(guess[15]==JAPAN)
    		  printf("Correct\nYour score is %d.",score+2);
    		else
    		  {printf("Wrong again\nTry once more");
    		     scanf("%s",&guess[15]);
    		      if(guess[15]==JAPAN)
    		      printf("right this time\nscore=%d",score+1);}
    		      break;
    	 default:
    	     printf("SORRY You LOST!\nyour score is %d.",score);
    	}
      }
     getch();
    }
    <snip>
    Code:
    void main()
    {
     char guess[15],JAPAN='q';
     int score=0;
    ...
    }
    This part of the code defines three variables. guess's type is an array of 15 characters the values of which are unknown at this point. The individual charaters in the array can be accessed by guess[0], guess[1], guess[2], ..., and guess[14]. JAPAN is a single char whose value is initially the value of the character 'q' in the execution character set. score is an int whose initial value is 0.

    Code:
    ...
         scanf("%s",&guess[15]);
    ...
    This will read a nul ('\0') terminated string into the buffer beginning at the address of the guess[15]. Oh, that's right, we only defined guess to have elements from 0 to 14. So this is guarranteed to write into memory that is not in the variable guess.
    Code:
    ...
         guess[15] = (guess[15]==JAPAN) ? 'a' : 'b';   /*conditional operator*/
    ...
    Similarly, this will compare the character guess[15] that does not exist to the character JAPAN. Based on those vaues, either 'a' or 'b' will be stored into guess[15] which does not exist.

    You need to read about arrays and strings which are arrays of char that are terminated by nuls ('\0').

    I did not review the rest of the code.
    Last edited by pheininger; 04-26-2011 at 05:53 AM. Reason: Correct nul character constant.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Lord Slytherin View Post
    Lord Slytherin@ CommonTater
    Lord Slytherin@ imalc
    Dears...

    I know that my poor Borland's Turbo C compiler has been abondoned fairly long time ago, however it still offers easy learning opportuinities to the beginners seeing that it was developed at the incipient stage of computer prgramming. As to the code capacity, there are 5 memory models (small,compact,medium,large and huge) which u could choose according to your scope, and by the way all of them accept code upto at least 64K and data storage of the same 64K limit.
    "It's good because it's old" only works with wine and some liquors... In the computer world it's terrible logic flaw... Old, very often means "useless"... which is what your compiler is... useless.

    Modern compilers like Pelles C will work anywhere within available memory... i.e. one string can be up to 2gb long, arrays can have up to 2giga elements and (for 64bit versions) addressing space is limited only by available memory.

    You do yourself a serius disservice sticking with a compiler that was written for Fred Flintstone and Barney Rubble.

  13. #13
    Registered User
    Join Date
    Apr 2011
    Location
    Karachi, Pakistan
    Posts
    19
    @Kmess

    Thanks for your briefing regarding the use of 'scanf'.

    scanf will properly terminate the input with the required null character ('\0')
    I dont get it. I think scanf terminates the input when u press the return key. This null character is unfamiliar to me. could u explain its operation...?

    Help shall always be given to those at Hogwarts who ask for it...!
    Albus Dumbledore
    Last edited by Lord Slytherin; 04-26-2011 at 02:19 PM.

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Lord Slytherin View Post
    I dont get it. I think scanf terminates the input when u press the return key. This null character is unfamiliar to me. could u explain its operation...?
    The C programming language has no strings... there is no native string type (like there is for int, float, double, etc). Instead C operates on arrays of a characters and library functions treat them as strings. Thus a string in C is of an unknown size (because C doesn't know how big arrays are). To prevent functions from running off the end of arrays, a trailing 0 is added to each string.

    Thus when you put "Hello" in a char array, you actually end up with "Hello\0"...

    For example: strlen() then simply counts how many characters before the 0 or strcpy() simply copies characters until it hits the 0.

    What kmess was telling you is most library functions, including scanf(), automatically insert the traling 0 when copying characters into your array.

  15. #15
    Registered User
    Join Date
    Apr 2011
    Location
    Karachi, Pakistan
    Posts
    19
    One thing more....

    You see I run my programme just recently, and when it asked the question I typed 'q' . Its result was that the programme run correctly this time. My answer ws accepted and I was awarded 4 points.
    Any explaintion for this...??

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can u guess my number?
    By hotsox in forum C Programming
    Replies: 2
    Last Post: 01-07-2006, 01:40 PM
  2. can u guess my number?
    By strider496 in forum C Programming
    Replies: 16
    Last Post: 03-22-2005, 10:19 PM