Thread: Caracter input

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    49

    Caracter input

    Hey guys, I was wondering if there was a way to scanf/getchar() a string of characters into a table ?
    Am i shooting for the stars or is it a possibility ?
    what I'm trying to do is basically have the user input 4 characters, that's pretty much all i need but when the user hits enter, the characters would be assigned to elements of a table...

    it should be doable i guess...

    it's part of a mastermind game I'm creating. the game is pretty much OK except for that question i ask.
    In the program, the user has 6 attempts at cracking a 4 color randomly picked code. normal way of running would be, user inputs 4 characters for red green blue and yellow (r, v, b, j - ie: rrbj - repetitions allowed)
    when user hits enter, program prints out the numbers of hit&miss colors... if any of course and will keep prompting to enter a new code till either the 6 retries are over or if the user guessed the code..

    My code is pretty much fine except for when a user enters a code... he either has to do each character at a time or enter the same code 4 times... which is not satisfactory.
    The program needs to read the 4 character string and put it in a table with a simple for loop.

    Here's my code
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    #define NBCOLORS 4
    #define NBTRIES 6
    
    char readkey();
    void createCode(char code[]);
    int playGame(char code[]);
    
    int main (void)
    {
        char secretCode[NBCOLORS];
        createCode(secretCode);
        while(playGame(secretCode));
        return 0;
    }
    
    
    // Character input/storage
    
    char readkey() {
        fflush(stdin);
        char c = '\n';
        while (c == '\n' || c == ' ')
            c = getchar();
        return c;
    }
    
    void createCode(char code[])
    {
        int i;
        srand(1810);
    
        /* create random code */
        for (i = 0; i < NBCOLORS; i++)
           switch(rand() &#37; 4)
           {
               case 0: code[i] = 'r'; break;
               case 1: code[i] = 'b'; break;
               case 2: code[i] = 'v'; break;
               case 3: code[i] = 'j'; break;
           }  
    }
    
    int playGame(char code[]) {
        char codeCopy[NBCOLORS];
        int victory = 0;
        int i, j, k;
        char c = 0;                         /* character being read */
        
            
        for (i = 0; i < NBTRIES; i++) {
            int identical = 0;
            int present = 0;
            
            for (j = 0; j < NBCOLORS; j++)
                codeCopy[j] = code[j];
            
            printf("Votre coup (essai no %i): ", i+1);
            
            for (j = 0; j < NBCOLORS; j++) {
                c = readkey();
                if (codeCopy[j] == c) {
                    codeCopy[j] = '#';
                    identical++;
                }
                else {
                    for(k = 0; k < NBCOLORS; k++)
                        if (codeCopy[k] == c) {
                            codeCopy[k] = '#';
                            present++;
                        }
                }
            }
            
            printf("Couleurs identiques: %i\n", identical);
            printf("Coleurs presentes: %i\n", present);
            
            if(identical == NBCOLORS) {
                printf("Bravo! Vous avez trouve notre sequence de couleurs\n");
                victory=1;
                break;
            }
        }
        
        if(!victory) {
            printf("Desole, la sequence de couleurs a deviner etait ");
            for (j = 0; j < NBCOLORS; j++)
                putchar(code[j]);
            putchar('\n');
        }
        
        while (c != 'o' && c != 'O' && c != 'n' && c != 'N') {
            fflush(stdin);
            printf("Voulez-vous jouer une autre partie? (O/N)?");
            c = readkey();
        }
        
        if (c == 'o' || c == 'O')
            return 1;
        return 0;
    }
    Thanks for any insight... this is puzzling me quite much
    Last edited by OrAnGeWorX; 12-13-2008 at 12:54 PM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The effects of fflush(stdin) aren't defined; even on the assumption that it does what you think it does, it's still a problem since you most emphatically don't want to blow away the input stream every time -- how else are they going to be able to type all four characters at one time if you keep throwing away all the other input?

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    well we were advised to use the fflush command so that no residual info is kept in memory at every code entry... i thought it was the right way to code this in.... the program works ok if the characters are entered 1 at a time followed by enter...

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Since the "residual info kept in memory" are the other three letters on the line that you wanted to read in, I would say that it is not the right way to do it. Provided you have a compiler that does the right thing with fflush(stdio) (a big if), you would only want to call it once before reading a code, not before every letter.

  5. #5
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i follow you but it's puzzling me more.
    i'm not really sure what to do now. Am i supposed to move the fflush command to the main? And why would c = getchar() only pick up 1 character at a time ? shouldn't it pick up the whole string?
    I'm using dev c++ with mingw if that answer your question about the compiler/dev environment

    thanks a whole bunch

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    getCHAR. getchar. Gets one character from the input string. I mean you're only assigning one character -- c doesn't have nearly enough room for the whole thing.

    And (un)fortunately the Windows runtime "supports" fflush(stdin), it seems; your code would probably work -- well, do what you want -- on my Mac machine, which doesn't flush stdin, and probably on a *nix machine as well. This is why we advise people to stay away from "extensions" where possible.

  7. #7
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    Quote Originally Posted by tabstop View Post
    getCHAR. getchar. Gets one character from the input string. I mean you're only assigning one character -- c doesn't have nearly enough room for the whole thing.
    so getchar() only picks up a character at a time, is there any other way i can pick up a whole string, then for loop it to place each character of the string in a table?

    And (un)fortunately the Windows runtime "supports" fflush(stdin), it seems; your code would probably work -- well, do what you want -- on my Mac machine, which doesn't flush stdin, and probably on a *nix machine as well. This is why we advise people to stay away from "extensions" where possible.
    well it does work... not to my liking or the given directions but still, if the characters are put in one at a time followed by enter, everything is fine (or seems to be, at least)
    I would do what I wanted if I knew what that was, or what my options were... hence why I'm asking my questions...
    And excuse my ignorance on the topic but which extension are you talking about and all of this falls in the realm of the class outline... I'm only using what we've been taught.

    I appreciate your input

    edit:
    the output should look like this: (considering the secret code to be rjbb)
    Devinez la sequence de 4 couleurs chiosies (r: rouge, b: bleu, v: vert, j: jaune).
    Vous avez 6 essais pour devinez cette sequence.


    Votre coup (essai no 1): vvjr
    Couleurs identiques: 0
    Couleurs presentes: 2

    etc etc

    italique for program output
    bold for user input
    Last edited by OrAnGeWorX; 12-13-2008 at 04:16 PM. Reason: extra info

  8. #8
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The "extension" I speak of is "fflush(stdin)". In standard C, it does nothing (or more precisely, what it does is left unspecified; it need not do anything in particular) -- but some systems use it to discard extra input.

    You can use scanf with a %4s specifier to read in four characters at a time -- you must have an array to read them into though. (And your array has to be able to store five characters, since strings have a \0 character at the end.)

  9. #9
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i tried commenting fflush line and now it takes the whole string and gives out proper output
    so the fflush was not supposed to be there... it seems.

    i tried a few runs at the code, selecting o to do another set of colors and here's where I found out my secret code is not clearing, it needs to be reinitialized, i wonder what could be doing this, it should be "resetting" every time. I doubt it has anything to do with the fflush. any takes on that ?

  10. #10
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    How many times is createCode called?

  11. #11
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    just wanted to say thanks for baring with me, I'm just finding it hard to relate the material I'm being taught (in French) with what you're saying and a lot of what we're told seems to be a load of crap as I'm also corroborating what you're saying (advice and such), not that I'm doubting you... more like doubting our educators...

  12. #12
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    once in main...

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    And since it gets called once, how many different codes do you get?

  14. #14
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i get you, i need to call createCode at the point the program "restarts"
    in the playGame function... just having some issues coding it... i'm getting some syntax error befor char...

    Code:
    int playGame(char code[]) {
        char codeCopy[NBCOLORS];
        int victory = 0;
        int i, j, k;
        char c = 0;                         /* character being read */
        createCode(char code[]);  >>> added call to createCode results in syntax error before char
    edit:
    I've replaced the bolded the following lines
    char secretCode[NBCOLORS];
    createCode(secretCode);

    it still keeps the secretCode of the last "game"
    am i missing something
    /me scratches his head
    Last edited by OrAnGeWorX; 12-13-2008 at 07:36 PM.

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code:
    createCode(secretCode);
    Code:
    createCode(char code[]);
    [offkey]One of these things is not like the others, one of these things just doesn't belong[/offkey]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. continues input
    By Matty_Alan in forum C Programming
    Replies: 2
    Last Post: 06-22-2007, 10:04 PM
  2. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  3. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  4. Simple Console Input for Beginners
    By jlou in forum C++ Programming
    Replies: 0
    Last Post: 06-21-2005, 01:50 PM
  5. Help with Input Checking
    By Derek in forum C Programming
    Replies: 7
    Last Post: 06-17-2003, 03:07 AM