Like Tree2Likes

Asking Questions and answers lead to if statement

This is a discussion on Asking Questions and answers lead to if statement within the C Programming forums, part of the General Programming Boards category; Hi All I am a youth worker and I have a student with me and we are learning C together. ...

  1. #1
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9

    Asking Questions and answers lead to if statement

    Hi All

    I am a youth worker and I have a student with me and we are learning C together. However, we are hitting snags. We are currently trying to write a programme and we are in a whole heap of confusion. We have tried googling and either we are asking the wrong question or it isn't possible!

    What we would like to do is to ask how many people are playing the game and then from that question do a loop that allows them to enter players names. When played the game will then say Your turn John.

    Thanks

    Rich

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    So start with some of the basics.

    Code:
    #include <stdio.h>
    int main ( ) {
      int numPlayers;
      printf("How many players\n");
      scanf("%d",&numPlayers);
      printf("There are %d players\n",numPlayers);
      return 0;
    }
    And
    Code:
    #include <stdio.h>
    int main ( ) {
      char playerName[100];
      printf("What is your name\n");
      scanf("%s",playerName);
      printf("Hello %s\n",playerName);
      return 0;
    }
    Develop slowly, test often, and make regular backups when several new things are working together.
    A development process
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Thanks Salem

    That has got us going. I presume that we now need a loop to keep asking the question until the value numPlayers has finished?

    Rich

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    Sounds good to me - go for it!
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Thanks for all the help Salem. We got the loop working like this:

    Code:
    //
    //  main.c
    //  Not Yours
    //
    //  Created by Richard Brown on 12/10/2012.
    //  Copyright (c) 2012 Fishfingers Incorporated. All rights reserved.
    //
    
    
    #include <stdio.h>
    
    
    int main(void)
    {
    
     int i=(NULL);
     int dice;
     char c;
    char names[]={'bob','james','frank'};
    char arr[] = "code,bob,bill";
     int numPlayers;
     char playerName[100];
     int loopcount;
    
        numPlayers=0;
        loopcount=0;
    
    printf("How many players\n");
     scanf("%d",&numPlayers);
    printf("There are %d players\n",numPlayers);
    
     while(loopcount<numPlayers){
    
    printf("What is your name\n");
     scanf("%s",playerName);
     printf("Hello %s\n",playerName);
    
            loopcount++;
    
        }
    
     for(;;) {
    
     int i=0;
    
    printf("\n\nEnter the number of dice you require or Q to quit: ");
     scanf("%d", &dice);
    
     srand(time(NULL));
    
     while (i<dice ){
    
     printf("%d,", 1+rand()%6);
            i++;
    
        }
    
    
    // Convert to character value
     scanf("%c", &c);
     if (c == 'Q'||c == 'q')
     break;
    
        }
    
    
    }
    As you can see we have also added the game code we are using. So we now have the game asking us how many players and also asking names according to that number and then we get to the game. Our next step is integrating the names with the game. We're having a go but if you have any pointers to help us in the direction we go that would be great!

    Thanks

    Rich

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,632
    Good to see that. However, you need to indent your code properly, e.g.,
    Code:
    //
    //  main.c
    //  Not Yours
    //
    //  Created by Richard Brown on 12/10/2012.
    //  Copyright (c) 2012 Fishfingers Incorporated. All rights reserved.
    //
    
    
    #include <stdio.h>
    
    
    int main(void)
    {
        int i = (NULL);
        int dice;
        char c;
        char names[] = {'bob', 'james', 'frank'};
        char arr[] = "code,bob,bill";
        int numPlayers;
        char playerName[100];
        int loopcount;
    
        numPlayers = 0;
        loopcount = 0;
    
        printf("How many players\n");
        scanf("%d", &numPlayers);
        printf("There are %d players\n", numPlayers);
    
        while (loopcount < numPlayers) {
            printf("What is your name\n");
            scanf("%s", playerName);
            printf("Hello %s\n", playerName);
    
            loopcount++;
        }
    
        for (;;) {
            int i = 0;
    
            printf("\n\nEnter the number of dice you require or Q to quit: ");
            scanf("%d", &dice);
    
            srand(time(NULL));
    
            while (i < dice) {
                printf("%d,", 1 + rand() % 6);
                i++;
            }
    
            // Convert to character value
            scanf("%c", &c);
            if (c == 'Q' || c == 'q')
                break;
        }
    }
    Also, instead of this:
    Code:
    char names[] = {'bob', 'james', 'frank'};
    you probably intended to write:
    Code:
    char names[] = {"bob", "james", "frank"};
    Your while loop could have been replaced by a for loop. Your controlled infinite loop could have been replaced by a do while loop, though arguably when you add error checking and such the infinite loop version could be easier to write.

    Oh, and you should only call srand once, near the top of the main function. Note that NULL is a null pointer constant, so instead of:
    Code:
    int i = (NULL);
    you should have written:
    Code:
    int i = 0;
    but then you never use i until it is used in the infinite loop, where another variable named i is declared.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Thanks laserlight

    We have removed the char names they weren't doing anything and were old code. We have removed the int i =(NULL); as it was obsolete as well.

    We have added the dice=5; because we only want 5 dice.

    However, we only the dice to roll 13 times per person and to declare their name as it rolls. So we will take a look at getting the number of rolls sorted next. If we can get it to roll 13 times only then after that it is introducing the numPlayer variable to get it to roll numPlayer * 13.

    Thanks for the help.

    We're off to get the next bit right!

    Rich

  8. #8
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    We have moved on significantly this morning. Thanks for all the help we are receiving. The code now looks like this:

    Code:
    //
    //  main.c
    //  Not Yours
    //
    //  Created by Richard Brown on 12/10/2012.
    //  Copyright (c) 2012 Fishfingers Incorporated. All rights reserved.
    //
    
    
    #include <stdio.h>
    
    
    int main(void)
    {
     int dice;
     char c;
     int numPlayers;
     char playerName[100];
     int loopcount;
     int rolls;
    
        numPlayers = 0;
        loopcount = 0;
        rolls = 0;
        dice=5;
    
    printf("How many players\n");
     scanf("%d", &numPlayers);
    printf("There are %d players\n", numPlayers);
    
     while (loopcount < numPlayers) {
    printf("What is your name\n");
     scanf("%s", playerName);
     printf("Hello %s\n", playerName);
    
            loopcount++;
        }
    
     while (rolls < numPlayers*13+1) {
     int i = 0;
    
    printf("\n\nPress Q to quit or the big button that has an arrow on it to keep going: ");
    
     srand(time(NULL));
    
     while (i < dice) {
     printf("%d,", 1 + rand() % 6);
                i++;
    
            }
    
            rolls++;
    
    // Convert to character value
     scanf("%c", &c);
     if (c == 'Q' || c == 'q')
     break;
        }
    }
    


    So we now have the dice being rolled 13 times * the number of players and only 5 dice being rolled at each time. However, the random function no longer works as intended, it is rolling duplicates. :C And as such we have not connected the players name to each roll.

    However, this is exciting and we feel like we are achieving.

    Rich


  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,494
    When you post code, please make sure you "paste as text" and then review your post afterwards.
    It should look nicely indented in a fixed width font, as in post #6.

    > However, the random function no longer works as intended, it is rolling duplicates
    Remove the srand() from within the loop.
    Ideally, you do this only once, at the start of main.

    The next step to consider would be storing multiple player names.
    Eg.
    char playerNames[10][100];
    Stores up to 10 players.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Thanks Salem. Sorry for the posting code - will post as plain text.

    Not sure where we go from
    char playerNames[10][100];

    If you could give us pointers even to a google search that would be brilliant.

    Thanks

    Rich

  11. #11
    Registered User
    Join Date
    Oct 2011
    Posts
    838
    Instead of reading input using scanf(), you could read full lines (up to a limited length) using fgets(). If you use Linux or Mac OS X, then you could use getline() to get unlimited length lines even easier.

    Anyway, here is one very useful thing you could consider. I hope it is not too complicated.

    A helper function, get_line(), reads a line of input into an internal buffer (specially kept existing between function calls: static). It then removes any leading and trailing whitespace (think accidental spaces) and the newline characters, and returns a pointer to the string. (It can also save the length of the line into a size_t variable, if asked.)
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char *get_line(FILE *const input, size_t *const length)
    {
        static char buffer[1024];
        char   *p;
        size_t  n;
    
        /* Read a new line of input. */
        p = fgets(buffer, sizeof buffer, input);
        if (!p)
            return NULL;
    
        /* Skip leading whitespace characters. */
        p += strspn(p, "\t\n\v\f\r ");
    
        /* Find the newline char(s), */
        n = strcspn(p, "\n\r");
    
        /* Backtrack any whitespace characters, */
        while (n > 0 && 
               (p[n-1] == '\t' || p[n-1] == '\v' ||
                p[n-1] == '\f' || p[n-1] == ' '))
            n--;
    
        /* and trim them out. */
        p[n] = '\0';
    
        /* Length requested? */
        if (length)
            *length = n;
    
        /* We can return p only because it points to a buffer
         * that is marked static. Otherwise the buffer contents
         * would vanish when this function returns. */
        return p;
    }
    Now, if you wanted to start a game by asking the players names, you could do it like this:
    Code:
    #define  MAX_PLAYERS 32
    
    int main(void)
    {
        char *player_name[MAX_PLAYERS];
        int   players = 0;
        char *line;
        size_t len;
    
        do {
            printf("Enter player %d name, or an empty line if no more players:\n", 1 + players);
    
            line = get_line(stdin, &len);
            if (!line || !len)
                break;
    
            player_name[players] = strdup(line);
            if (!player_name[players]) {
                printf("Ouch; I ran out of memory. Sorry.\n");
                exit(1);
            }
    
            players++;
    
        } while (players < MAX_PLAYERS);
    
        if (players < 1) {
            printf("No players? Okay.\n");
            exit(0);
        }
        if (players >= MAX_PLAYERS) {
            printf("All player seats are now taken!\n");
        }
    
        /* Rest of main() ... */
    Since the name is a full line, you can have spaces in players' names. Useful if you have two or more with similar/same first names!

    Because the line buffer is reused for each line, you need to use strdup() to save the persons name for future use. Technically, we should also call free() to free each one after we no longer need them, but since the operating system will do that when the program exits, we don't need to bother with that for the names.

    If you were to ask (and save) a player for a number between 1 and 10, inclusive, you could do it like this:
    Code:
        int player_number[MAX_PLAYERS];
        int player;
    
        player = 0;
        do {
            printf("Your turn, %s. Input a number between 1 and 10, inclusive.\n", player_name[player]);
    
            line = get_line(stdin, NULL);
            if (!line) {
                printf("Aborted.\n");
                exit(1);
            }
    
            if (sscanf(line, "%d", &player_number[player]) < 1) {
                printf("%s is not a number to me, %s. Try again, please.\n", line, player_name[player]);
                continue;
            }
            if (player_number[player] < 1) {
                printf("%s is too small, %s. It must be 1 or greater. Try again, please.\n", line, player_name[player]);
                continue;
            }
            if (player_number[player] > 10) {
                printf("%s is too large, %s. It must be 10 or less. Try again, please.\n", line, player_name[player]);
                continue;
            }
    
            printf("%s chose number %d.\n", player_name[player], player_number[player]);
    
            /* Advance to next player, but go back to 0 at players.
             * % means "the remainder of left side, when divided by right side",
             * also known as the modulus operator.
            */
            player = (player + 1) % players;
    
            /* but only do one round; stop when player == 0. */
        } while (player != 0);
    After the round, you have the numbers they chose in player_number[0 .. players-1]. It is not a for loop, as you couldn't then retry as easily. Since we only move to the next player at the very end of the loop body, we can retry by simply using continue, which just skips to the start of the next iteration. (If we use a for loop, the loop variable would have been updated -- giving us the next player instead.)

  12. #12
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,344
    WOW - That must be a lot to take in from Nominal Animal!


    Storing strings is a good goal from here.


    You will need to know about arrays and strings.


    "scanf" is a good way of getting strings from the user, but as Nominal Animal hinted - fgets is the best way (you might want to look it up after you get this program working).


    I tried to look for an easy example for you, but I couldn't find it, so I quickly put one together for you


    Code:
    
    #include <stdio.h>
    #include <string.h>
    // (Note that string.h is not needed yet, 
    //  but it is very good to get to know these functions)
    
    
    int main(void)
    {
        int i;
        char user_names[10][20];
        
        /* Start at i=0, keep looping until i<10 is no longer true, increment i each time */
        for (i=0; i<10; i++)
        {
            /* Prompt for next name */
            printf ("\nEnter name %d:", (i+1) );
    
    
            /* Store new name in array */
            /* Note that max input length is now 19 characters */
            scanf("%19s", user_names[i]);
    
    
        }
    
    
        /* Print out all the names */
        for (i=0; i<10; i++)
        {
            printf("%s \n", user_names[i]);
        }
    
        /* You must always have this at the end of your main function: */
        return 0;
    
    
    }
    Fact - Beethoven wrote his first symphony in C

  13. #13
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Morning All

    Thanks for all the replies. I have to admit to being a bit overwhelmed by Nominal Animal's code. I will be working through it with the young people. Thanks so much for posting it.

    Click_here's code is much more understandable and helps us to achieve a list of players names. We will endeavour to incorporate this code and Nominal Animal's to see if we can achieve our aim of players rounds.

    Thanks once again for all the help.

    Rich

  14. #14
    Registered User
    Join Date
    Oct 2012
    Location
    Lostwithiel, Cornwall
    Posts
    9
    Still struggling to understand this and maybe we need to go and build a lego tower or something! But we would love to understand this. So with Click_Here's code we end up with a print out of all user_names but what we want is for that output to a single string. i.e. John....... then something happens, jeremy......... then next thing happens and finally Jenny........ and we get another thing happening.

    We have read around fgets and can't see how this applies. We tried making it a if loop and nope it didn't work. We tried adding a while statement but still ran into problems.

    Can we have a key here please?

    Thanks

    Rich

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,632
    What is your current code, your exact test input, expected output and actual output?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calculating Target Lead
    By Jesse Richards in forum Game Programming
    Replies: 2
    Last Post: 09-05-2012, 06:37 PM
  2. questions and answers from a file
    By jaralvarado in forum C Programming
    Replies: 10
    Last Post: 07-24-2011, 10:10 AM
  3. questions on following statement
    By sanddune008 in forum C Programming
    Replies: 5
    Last Post: 07-30-2010, 03:14 AM
  4. Giving Whole Answers to Questions
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 59
    Last Post: 01-30-2005, 09:26 PM
  5. Rookie needs a lead
    By DirtElk in forum C Programming
    Replies: 5
    Last Post: 02-18-2002, 07:27 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21