views:

126

answers:

3
    #include <stdio.h>
#include <stdlib.h>
#include <time.h>

void initDeck (int deck[]);
void showDeck (int deck[]);
void shuffleDeck (int deck[]);
int getBet ();

main()
{
    int deck[52];
    int playerBet;
    char z;
    initDeck(deck);
    shuffleDeck(deck);
    showDeck(deck);
    playerBet = getBet();
    //scanf ("%d\n", &playerBet);
    printf("%d\n", playerBet);
    z = 1;
    getchar(z);

    return 0;
}

void initDeck (int deck[]){
    int k;
    int i;
    for (k = 1; k < 53; k++){
     i = k - 1;
     deck[i] = k;
    }
    return;
}

void showDeck (int deck[]){
    int k;
    for (k = 0; k < 52; k++){
     printf("%d\n", deck[k]);
    }
    return;
}

void shuffleDeck (int deck[]){
    int random;
    int k;
    int temp;
    srand(time(0));
    for (k = 52; k > 1; k--){ 
     random = (rand() % k) + 1;
     if (random != k){
      temp = deck[k - 1];
      deck[k - 1] = deck[random - 1];
      deck[random- 1] = temp;
     }
     else{
      k++;
      continue;
     }
    }


    return;
}

int getBet (){
    int bet;
    scanf ("%d\n", &bet);
    return bet;
}

The function at issue is getBet() and when I input an integer it doesn't give me any output. I tried doing the input in main and it worked, but I don't see the problem with this. I've double checked for small errors a few times, and I don't see anything wrong with it...

A: 

I also don't see the error. Why don't you pass it by address instead?

int main()
{
   int playerBet;
   //
   getBet(&playerBet);
}

void getBet(int* bet)
{
   scanf("%d", bet);
}

I don't do C, but that is the general idea.

Hooked
Shouldn't then it be 'void getBet(int* bet)'?
quosoo
Oh yes, good point. Fixed.
Hooked
+2  A: 

Instead of

scanf("%d\n", &bet);

do

scanf("%d", &bet);

Just tested and it works.

Artem Barger
It works but I don't necessarily understand why. In the main function it was the same line and yet it worked. And without the \n the program closes right away since (for reasons unknown to me) the getchar command doesn't stop it.
You can read the post of Martin beneath, he made a good explanation.
Artem Barger
+4  A: 

The problem is that you end your scanf string with a newline. This means (read the scanf documentation) any amount of whitespace. So when you enter "" it still waits for more white space. Try entering non-whitespace characters afterwards to see it accept the input. As Artem says, omitting the \n could be one solution.

Martin v. Löwis