• Welcome to Valhalla Legends Archive.
 

Starting out with C... a little help would be lovely...

Started by Barabajagal, July 09, 2008, 03:10 AM

Previous topic - Next topic

Barabajagal

#include <stdio.h>
int answer;
int guess;
int main()
{
  srand (time(NULL));
  int playing = 1;
  while (playing == 1)
  { 
    newGame();
    while (guess != answer)
    {
      getGuess();
      if (checkGuess() == 1)
      {
        char string;
        printf("Would you like to play again? (Y/N)");
        string = getchar();
        if (string == 'n')
        {
          playing = 0;
        }
        else
        {
          playing = 1;
        }
      }
    }
  }
  return 0;
}
int newGame()
{
  answer = rand() % 100 + 1;
  printf("I'm thinking of a number between 1 and 100 (%d)\n", answer);
  return 0;
}
int getGuess()
{
  printf("What's your guess?\n");
  scanf("%d", &guess);
  return 0;
}
int checkGuess()
{
  if (guess > answer)
  {
    printf("Your guess is a little high...\n");
    return 0;
  }
  else if(guess < answer)
  {
    printf("Your guess is a little low...\n");
    return 0;
  }
  else
  {
    printf("You guessed it!\n");
    return 1;
  }
}

here's my little guessing game app... not much, and not working. It doesn't pause for getchar(), and when doing some tests, I realize I have no idea how to use getchar correctly. It doesn't seem to function rationally.

As a test, I did the following:
#include <stdio.h>
int main()
{
  int playing = 0;
  while (playing == 0)
  {
   char string;
   printf("Would you like to play? (Y/N)");
   string = getchar();
   if (string == 'y')
   {
     playing = 1;
   }
   else
   {
     playing = 0;
   } 
   printf ("\n");
  }
}

As you can find out yourself, typing n and enter causes it to prompt twice, effectively ignoring getchar once entirely. I really don't get it.

brew

getchar() doesn't return until the enter key has been pressed. Then, it consecutively is called once for every character entered, plus the \n from the enter. Put in another getchar() to move along the character "stack". If you're still completely clueless you might want to use fgets() with stdin, then just deal with buffer[0]. By the way, a char in itself is not a string. a char is an 8 bit numerical value.
And might i add, the actual program logic is very poorly thought out. Although this has nothing to do with not knowing C well...

If you don't mind me asking, why are you trying to learn C? I thought PowerBASIC was superior! If you'd really like to move onto another language, I'd recommend C# .NET. .NET is the way of the future, you know?
<3 Zorm
Quote[01:08:05 AM] <@Zorm> haha, me get pussy? don't kid yourself quik
Scio te esse, sed quid sumne? :P

shout

I recommend using cin / cout when learning C.

getchar() MSDN documentation

Edit:

Looking at your code a little more, I see you are using scanf to get the number that was guessed. Why not use scanf to get the y/n answer? I wouldn't call myself a C programmer, but I think the answer and guess variables should be inside of main and passed to checkGuess(). newGame() could return the random number. Example: (sorry for the formatting)


int main()
{
/*stuff*/
int answer = newGame();
int guess = 0;
/*more stuff*/
guess = getGuess();
/*Even more stuff*/
if (checkGuess(guess) == 1)
/*the rest of the stuff*/
}

brew

<3 Zorm
Quote[01:08:05 AM] <@Zorm> haha, me get pussy? don't kid yourself quik
Scio te esse, sed quid sumne? :P

l2k-Shadow

Quote from: replaced on November 04, 2006, 11:54 AM
I dunno wat it means, someone tell me whats ix86 and pmac?
Can someone send me a working bot source (with bnls support) to my email?  Then help me copy and paste it to my bot? ;D
Já jsem byl určenej abych tady žil,
Dával si ovar, křen a k tomu pivo pil.
Tam by ses povídaj jak prase v žitě měl,
Já nechci před nikym sednout si na prdel.

Já nejsem z USA, já nejsem z USA, já vážně nejsem z USA... a snad se proto na mě nezloběj.

Barabajagal

1) I'm not ever going to use a .NET language. Ever. I'm planning to move my development to win and lin, in C and C++.
2) I want to learn C first, so when I get into C++, it'll be easy.
3) The reason I'm not sticking with PB is because there aren't any freelance jobs that use it.
4) Thank you guys for explaining, my new code is now:
#include <stdio.h>
int main()
{
  int playing = 1;
  srand (time(NULL));
  while (playing == 1)
  { 
    int answer = newGame();
    int guess;
    while (guess != answer)
    {
      guess = getGuess();
      if (checkGuess(guess, answer) == 1)
      {
        char again[0];
        printf("Would you like to play again? (Y/N)");
        scanf("%s", again);
        if (again[0] == 'n')
        {
          playing = 0;
        }
      }
    }
  }
  return 0;
}
int newGame()
{
  int answer = rand() % 100 + 1;
  printf("I'm thinking of a number between 1 and 100 (%d)\n", answer);
  return answer;
}
int getGuess()
{
  int guess;
  printf("What's your guess?\n");
  scanf("%d", &guess);
  return guess;
}
int checkGuess(int guess, int answer)
{
  if (guess > answer)
  {
    printf("Your guess is a little high...\n");
    return 0;
  }
  else if(guess < answer)
  {
    printf("Your guess is a little low...\n");
    return 0;
  }
  else
  {
    printf("You guessed it!\n");
    return 1;
  }
}

and it works just fine!

l2k-Shadow

char again[0] <- lol

i would like to point out that arrays in C differ from VB in the way that the number in brackets defines the size of the array not the upper bound like it does in VB.

so char s[20] goes from s[0] to s[19].
Quote from: replaced on November 04, 2006, 11:54 AM
I dunno wat it means, someone tell me whats ix86 and pmac?
Can someone send me a working bot source (with bnls support) to my email?  Then help me copy and paste it to my bot? ;D
Já jsem byl určenej abych tady žil,
Dával si ovar, křen a k tomu pivo pil.
Tam by ses povídaj jak prase v žitě měl,
Já nechci před nikym sednout si na prdel.

Já nejsem z USA, já nejsem z USA, já vážně nejsem z USA... a snad se proto na mě nezloběj.

Barabajagal

Mm... I wanted to just do char again;, but it crashed. This works, and I don't know why if that's the case. I'm gonna go to the library and get some books on C, cause I really don't know anything about this.

l2k-Shadow

#8
Quote from: Andy on July 09, 2008, 05:24 PM
Mm... I wanted to just do char again;, but it crashed. This works, and I don't know why if that's the case. I'm gonna go to the library and get some books on C, cause I really don't know anything about this.

note that in C, strings are character arrays ending with a null byte, so for each string you must allocate at least 2 bytes. using char again; - you wrote the null byte into an unallocated segment of memory with the scanf() function.
Quote from: replaced on November 04, 2006, 11:54 AM
I dunno wat it means, someone tell me whats ix86 and pmac?
Can someone send me a working bot source (with bnls support) to my email?  Then help me copy and paste it to my bot? ;D
Já jsem byl určenej abych tady žil,
Dával si ovar, křen a k tomu pivo pil.
Tam by ses povídaj jak prase v žitě měl,
Já nechci před nikym sednout si na prdel.

Já nejsem z USA, já nejsem z USA, já vážně nejsem z USA... a snad se proto na mě nezloběj.

brew

Quote from: l2k-Shadow on July 09, 2008, 05:34 PM
wrote the null byte into an unallocated segment of memory with the scanf() function.
Unallocated? Take a look at the variable defintion(s) above char again- you'll see he declared int playing, int answer, and guess, giving him 12 bytes of space. He probably never dreamed of typing more than 11 chars, so he would have never found the near-fatal bug.
@RealityRipple: You're missing the entire point of scanf's destination param! It expects a pointer to w/e it's writing, and where again was defined as char again[0], it would be the base address of that array (consequentially, since it's a zero-length data block, its address would be the same as guess's). However, since you redefined again as a char, and not a char [], you were passing the value of again where the address of again was expected. If you insist on using a char, try using the & address of operator. Also, stop trying to write strings in a single byte of space! 3 bytes are written even if you input just one character- the \n and the null terminator.
Solution: Make your again variable an array with at the very least 16 bytes. That's seemingly an appropriate size. Then, you should stop using dangerous functions! Try scanf_s() instead of scanf().
<3 Zorm
Quote[01:08:05 AM] <@Zorm> haha, me get pussy? don't kid yourself quik
Scio te esse, sed quid sumne? :P

l2k-Shadow

well yes, but you don't want to overwrite other variables inside the program, hence the space wasn't allocated for that particular variable.
Quote from: replaced on November 04, 2006, 11:54 AM
I dunno wat it means, someone tell me whats ix86 and pmac?
Can someone send me a working bot source (with bnls support) to my email?  Then help me copy and paste it to my bot? ;D
Já jsem byl určenej abych tady žil,
Dával si ovar, křen a k tomu pivo pil.
Tam by ses povídaj jak prase v žitě měl,
Já nechci před nikym sednout si na prdel.

Já nejsem z USA, já nejsem z USA, já vážně nejsem z USA... a snad se proto na mě nezloběj.

Barabajagal

Changed it to char again[0x0F];. scanf_s? I don't see that in the C documentation anywhere.

brew

scanf_s() is the safe version of scanf(). Also, I hope you do realize that this is not vb6- you do not define the "ubound" of the array on declaration, but instead the number of elements. Just to let you know.








.
.
.
unless you intended for again to be a 15 byte char array (kind of an odd number, eh?)
<3 Zorm
Quote[01:08:05 AM] <@Zorm> haha, me get pussy? don't kid yourself quik
Scio te esse, sed quid sumne? :P

Barabajagal

Since it's only ever going to be a Y or N, does it matter?
And scanf_s() is undefined. Likely it's not C or it's a MS proprietary function (my compiler is GCC).

K

If you're only planning on reading one character, then you probably don't want to use the '%s' specifier, but '%c' which means one character.

scanf_s as far as I can tell is the 'safer C' version of scanf provided by MS, which probably isn't portable.