Advertisement
Guest User

Untitled

a guest
Feb 11th, 2013
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define FGETSADDCHARS 2; //accounts for additional characters fgets adds to our string
  6.  
  7. void flushBuffer();
  8. char *getInput(int max, char message[]);
  9. char *getInputNoNewline(int max, char message[]);
  10.  
  11. typedef struct Person {
  12.     char *firstName;
  13.     char *lastName;
  14.     int yob;
  15. } Person;
  16.  
  17. void flushBuffer() {
  18.     int ch;
  19.     while ((ch = getchar()) != '\n' && ch != EOF); //flush the input buffer
  20. }
  21.  
  22. char *getInput(int max, char message[]) {
  23.     char *in;
  24.     int maxchars = max+FGETSADDCHARS;
  25.     in = malloc(maxchars * sizeof(char));
  26.     char *input;
  27.     do {
  28.         printf("%s", message);
  29.         input = fgets(in, (maxchars), stdin);
  30.         if (in[strlen(in)-1] != '\n') {
  31.             printf("Sorry, maximum %d characters\n", (max));
  32.             flushBuffer();
  33.         }
  34.     } while (in[(strlen(in)-1)] != '\n');
  35.     return in;
  36. }
  37.  
  38. char *getInputNoNewline(int max, char message[]) {
  39.     char *input;
  40.     int len;
  41.     input = getInput(max, message);
  42.     len = strlen(input);
  43.     if (input[len - 1] == '\n' && len > 0) { //strip new line character
  44.         input[len - 1] = '\0';
  45.     }
  46.     return input;
  47. }
  48.  
  49. int main(int argc, char *argv[]) {
  50.     int numPlayers = 3;
  51.     char *intIn;
  52.     int i = 0;
  53.     struct Person *players = malloc (numPlayers * sizeof *players);
  54.  
  55.     printf("Hello world Game\n");
  56.     for (i = 0; i < numPlayers; ++i) {
  57.         players[i].firstName = getInputNoNewline(50, "What is your first name: ");
  58.         printf("%s\n", players[i].firstName);
  59.         players[i].lastName = getInputNoNewline(80, "What is your last name: ");
  60.         printf("%s\n", players[i].lastName);
  61.         intIn = getInputNoNewline(4, "What is your YOB: "); //TODO: convert number to integer with sscanf
  62.         printf("%s\n", intIn);
  63.         printf("-----------------------------------\n");
  64.     }
  65.     printf("Finished\n");
  66.     if (players != NULL) free(players);
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement