mackal

dice.c

Jan 2nd, 2012
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | None | 0 0
  1. // dice.c: Rolls a dice, input in the manner of 1d6
  2. // Abritrary dice and sides can be entered
  3. // -----------------------------------------------------------------------------
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7. #include <string.h>
  8.  
  9. void roll(int dice, int sides);
  10. int main (int argc, char *argv[])
  11. {
  12.     int dice, sides;
  13.     // Simple error checking on arguments
  14.     if ( argc != 2 )
  15.     {
  16.         fprintf(stderr, "You must enter one argument. ex:\n");
  17.         fprintf(stderr, "\tdice 1d6\n");
  18.         return 1;
  19.     }
  20.  
  21.     srand((unsigned)time(NULL));  // Init seed for random numbers
  22.  
  23.     // Parse input
  24.     dice = strtol(strtok(argv[1], "d"), NULL, 10);
  25.     sides = strtol(strtok(NULL, "\n"), NULL, 10);
  26.    
  27.     // Roll dem fucking dice.
  28.     roll(dice, sides);
  29.     return 0;
  30. }
  31.  
  32. void roll(int dice, int sides)
  33. {
  34.     int i, result, total = 0;
  35.     for ( i=0; i < dice; i++)
  36.     {
  37.         result = 1 + rand() % sides;    // Would be between 0 and 5 without + 1
  38.         printf("Die %d: %d\n", i + 1, result);
  39.         total += result;
  40.     }
  41.     printf("Total: %d\n", total);
  42.     return;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment