Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define FGETSADDCHARS 2; //accounts for additional characters fgets adds to our string
- void flushBuffer();
- char *getInput(int max, char message[]);
- char *getInputNoNewline(int max, char message[]);
- typedef struct Person {
- char *firstName;
- char *lastName;
- int yob;
- } Person;
- void flushBuffer() {
- int ch;
- while ((ch = getchar()) != '\n' && ch != EOF); //flush the input buffer
- }
- char *getInput(int max, char message[]) {
- char *in;
- int maxchars = max+FGETSADDCHARS;
- in = malloc(maxchars * sizeof(char));
- char *input;
- do {
- printf("%s", message);
- input = fgets(in, (maxchars), stdin);
- if (in[strlen(in)-1] != '\n') {
- printf("Sorry, maximum %d characters\n", (max));
- flushBuffer();
- }
- } while (in[(strlen(in)-1)] != '\n');
- return in;
- }
- char *getInputNoNewline(int max, char message[]) {
- char *input;
- int len;
- input = getInput(max, message);
- len = strlen(input);
- if (input[len - 1] == '\n' && len > 0) { //strip new line character
- input[len - 1] = '\0';
- }
- return input;
- }
- int main(int argc, char *argv[]) {
- int numPlayers = 3;
- char *intIn;
- int i = 0;
- struct Person *players = malloc (numPlayers * sizeof *players);
- printf("Hello world Game\n");
- for (i = 0; i < numPlayers; ++i) {
- players[i].firstName = getInputNoNewline(50, "What is your first name: ");
- printf("%s\n", players[i].firstName);
- players[i].lastName = getInputNoNewline(80, "What is your last name: ");
- printf("%s\n", players[i].lastName);
- intIn = getInputNoNewline(4, "What is your YOB: "); //TODO: convert number to integer with sscanf
- printf("%s\n", intIn);
- printf("-----------------------------------\n");
- }
- printf("Finished\n");
- if (players != NULL) free(players);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement