Program exiting

This is a discussion on Program exiting within the C Programming forums, part of the General Programming Boards category; ok...this is my question, when using scanf() to read inputs, u need to use getchar() after scanf() or else if ...

  1. #1
    Deleted Account
    Join Date
    Mar 2005
    Posts
    57

    Program exiting

    ok...this is my question, when using scanf() to read inputs, u need to use getchar() after scanf() or else if u enter something, window will close immediately? now i've started to use fgets() and the same thing happens, how do i fix it?

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,671
    By only using fgets() for input.
    If you mix getchar(), scanf() and fgets() all in the same program, then you'll always have problems deciding whether you need to 'flush the input or not'

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    After a scanf() call, you need to flush the buffer (with something like this, not with fflush(stdin)):
    Code:
    void flush_buffer(void) {
        int c;
    
        while((c = getchar()) != '\n' && c != EOF);
    }
    fgets() reads the newline, so you don't need to (in fact shouldn't) flush the buffer after it.

    If you want to keep the window open, read the FAQ. (Hint: call flush_buffer() twice.)
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Deleted Account
    Join Date
    Mar 2005
    Posts
    57
    ok..this is wat my pgrm looks like atm..yea...and pgrm exits everytime i input something and press enter

    Code:
    #include "hangman.h"
    
    /****************************************************************************
    * Function main() is the entry point for the program.
    ****************************************************************************/
    int main(void)
    {
       char word[MAX_WORD_LEN + 1];
       unsigned wrongGuesses = 0;
       int guessedLetters[ALPHABET_SIZE] = {
          0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
       };
       init(word);
    
       do   
       {
          displayWord(word, guessedLetters);
          if(guessLetter(word, guessedLetters) == BAD_GUESS) 
             wrongGuesses++;
          displayHangman(wrongGuesses);
       }  while(isGameOver(word, guessedLetters, wrongGuesses) != GAME_OVER);
       
       return EXIT_SUCCESS;
    }
    
    
    /****************************************************************************
    * Function init() choses a word for the hangman game from the words[] array.
    ****************************************************************************/
    void init(char* word)
    {
       const char* words[NUM_WORDS] = {
          "array",      "auto",       "break",      "case",       "cast",
          "character",  "comment",    "compiler",   "constant",   "continue",
          "default",    "double",     "dynamic",    "else",       "enum",
          "expression", "extern",     "file",       "float",      "function",
          "goto",       "heap",       "identifier", "library",    "linker",
          "long",       "macro",      "operand",    "operator",   "pointer",
          "prototype",  "recursion",  "register",   "return",     "short",
          "signed",     "sizeof",     "stack",      "statement",  "static",
          "string",     "struct",     "switch",     "typedef",    "union",
          "unsigned",   "variable",   "void",       "volatile",   "while"
       };
       srand(time(NULL));
       strcpy(word, words[rand() % NUM_WORDS]);
       
    }
    
    
    /****************************************************************************
    * Function displayWord() prints the word to screen with all letters that 
    * have not been correctly guessed blanked out with an underscore. 
    * Output example:
    * +-+-+-+-+-+-+-+-+-+-+
    * |i|d|e|n|_|i|_|i|e|r|
    * +-+-+-+-+-+-+-+-+-+-+
    ****************************************************************************/
    void displayWord(char* word, int* guessedLetters)
    {
       char *ptr;
       for(ptr=word; *ptr !='\0'; ptr++)
       {
          if(guessedLetters[*ptr-'a'] = 1)
             printf("%c", *ptr);
          else
             printf("-");
       } 
            
    }
    
    
    /****************************************************************************
    * Function guessLetter() prompts the user to enter one letter. The function
    * maintains an array of guessed letters. The function returns GOOD_GUESS
    * or BAD_GUESS depending on whether or not the letter is in the word.
    ****************************************************************************/
    int guessLetter(char* word, int* guessedLetters)
    {
        char guess[3];
        char *ptr = word;
        int result = BAD_GUESS;
        int valid = FALSE;
        do
        {
           printf("\nEnter a letter: ");
           fgets(guess, 3, stdin);
           valid = isValid(guess);
           if(valid == TRUE)
           {
              if(guess[0] < 'a' || guess[0] > 'z')
              {
                 valid = FALSE;
                 printf("Invalid characters, try again!");
              }
           }
         } while(valid = FALSE);
         
           for(ptr=word; *ptr !='\0'; ptr++)
           {
           if(guess[0] == *ptr)
           {
              guessedLetters[(int)guess[0] - 'a'] = 1;
              result = GOOD_GUESS;
              break;
           }
        }
    
        if(result == BAD_GUESS)
        {
           guessedLetters[(int)guess[0] - 'a'] = 2;
           printf("\nWrong Guess, Please try again!\n");
        }
        return result;
    }
    
    
    /****************************************************************************
    * Function displayHangman() displays an ascii art drawing to complement the
    * game. The drawing varies depending on the number of wrong guesses.
    * When there are no wrong guesses, an empty drawing is displayed:
    * **********
    * *        *
    * *        *
    * *        *
    * *        *
    * *        *
    * *        *
    * **********
    * When there are 10 wrong guesses (and the game is over), the complete
    * drawing is displayed:
    * **********
    * * +--+   *
    * * |  |   *
    * * |  O   *
    * * | -+-  *
    * * | / \  *
    * * +----- *
    * **********
    * You need to display an appropriate drawing depending on the number of 
    * wrong guesses:
    * - 0 wrong: empty drawing.
    * - 1 wrong: include floor.
    * - 2 wrong: include vertical beam.
    * - 3 wrong: include horizontal beam.
    * - 4 wrong: include noose.
    * - 5 wrong: include head.
    * - 6 wrong: include body.
    * - 7 wrong: include left arm.
    * - 8 wrong: include right arm.
    * - 9 wrong: include left leg.
    * - 10 wrong: include right leg (complete drawing).
    ****************************************************************************/
    void displayHangman(unsigned wrongGuesses)
    {
         if(wrongGuesses == 1)
            printf("-----");
         else if(wrongGuesses == 2)
            printf("+\n|\n|\n|\n|\n+-----");
         else if(wrongGuesses == 3)
            printf("+--+\n|\n|\n|\n|\n+-----");
         else if(wrongGuesses == 4)
            printf("+--+\n|  |\n|\n|\n|\n+-----");
         else if(wrongGuesses == 5)
            printf("+--+\n|  |\n|  o\n|\n|\n+-----");
         else if(wrongGuesses == 6)
            printf("+--+\n|  |\n|  o\n|  +\n|\n+-----");
         else if(wrongGuesses == 7)
            printf("+--+\n|  |\n|  o\n| -+\n|\n+-----");
         else if(wrongGuesses == 8)
            printf("+--+\n|  |\n|  o\n| -+-\n|\n+-----");
         else if(wrongGuesses == 9)
            printf("+--+\n|  |\n|  o\n| -+-\n| /\n+-----");
         else if(wrongGuesses == 10)
            printf("+--+\n|  |\n|  o\n| -+-\n| // \n+-----");
    }
    
    
    /****************************************************************************
    * Function isGameOver() is the final step in the program. The game is over
    * if either all letters in the word have been guessed, or the player has run
    * out of guesses. The player is congratulated if he/she wins. The word is
    * displayed to the player if he/she loses. This function returns either 
    * GAME_OVER or GAME_CONTINUE.
    ****************************************************************************/
    int isGameOver(char* word, int* guessedLetters, unsigned wrongGuesses)
    {
        int noWords = 0;
        int i;
        for(i=0; i<ALPHABET_SIZE; i++)
        {
           if(guessedLetters[i] == 1)
              noWords++;
        }
        
        if(noWords = strlen(word))
        {
           printf("Congratulations! You have guessed the word!");
           return GAME_OVER;
        }
        
        if(wrongGuesses >= MAX_GUESS)
        {
           printf("You have exceeded the number of allocated guesses! Game Over!");
           return GAME_OVER;
        }
        else
           GAME_CONTINUE;
    }
    
    
    /****************************************************************************
    * Function readRestOfLine() is used for buffer clearing. Source: 
    * https://inside.cs.rmit.edu.au/~sdb/teaching/C-Prog/CourseDocuments/
    * FrequentlyAskedQuestions/
    ****************************************************************************/
    void readRestOfLine()
    {
       int c;
    
       /* Read until the end of the line or end-of-file. */   
       while ((c = fgetc(stdin)) != '\n' && c != EOF)
          ;
    
       /* Clear the error and end-of-file flags. */
       clearerr(stdin);
    }
    
    int isValid(char *input)
    {
        int valid = FALSE;
        if(input[strlen(input)-1] != '\n')
        {
           printf("Input too long, please try again!");
           readRestOfLine();
        }
        else
        {
            input[strlen(input)-1] = '\0';
            valid = TRUE;
        }
        return valid;
    }
    Last edited by sql.scripter; 01-28-2006 at 04:20 PM.

  5. #5
    Registered User
    Join Date
    Dec 2005
    Posts
    52
    wow. i'm pretty sure i know why.
    but then again, i didn't read your code and it could have actual problems in it.

    are you using some windows(BLEHHH) IDE?
    if so, do you just click "run"?
    if so, it opens a console window, runs your program, and closes it after you hit enter because the program finishes.

    Try compiling from a command prompt and running the executable from there.

  6. #6
    Deleted Account
    Join Date
    Mar 2005
    Posts
    57
    ok...will try...but my friend posted his program and i compiled with my compiler (dev c++ ) and it worked...hmm..so i dun think it's the problem...?
    Last edited by sql.scripter; 01-28-2006 at 04:45 PM.

  7. #7
    old man
    Join Date
    Dec 2005
    Posts
    90
    Code:
        do
        {
        /* ... */
        } while(valid = FALSE);
    You're accidentally doing an assignment here; you want '=='

  8. #8
    Deleted Account
    Join Date
    Mar 2005
    Posts
    57
    man, this is so annoying..lol..still exiting..but i juz found it doesn't if u input more than one character, i.e ab
    Last edited by sql.scripter; 01-28-2006 at 06:12 PM.

  9. #9
    old man
    Join Date
    Dec 2005
    Posts
    90
    Code:
        /* assignment instead of comparison */
        if(guessedLetters[*ptr-'a'] = 1)
    
        /* assignment instead of comparison */
        if(noWords = strlen(word))
     
        /* you forgot to use 'return' here */
        else
           GAME_CONTINUE;
    You need to work on your proof-reading.

  10. #10
    Deleted Account
    Join Date
    Mar 2005
    Posts
    57
    heheh...sorri, i've been lazy a bit..yea..juz tryin to practice a past assignments for my course before i start it in a month time...

    thanks alot..there was a few more of these mistakes somewhere else..but yea..all fixed..thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can someome help me with a program please?
    By WinterInChicago in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2006, 10:58 PM
  2. exiting program
    By ypramesh in forum C Programming
    Replies: 2
    Last Post: 04-01-2006, 02:27 PM
  3. Need help with my program...
    By Noah in forum C Programming
    Replies: 2
    Last Post: 03-11-2006, 06:49 PM
  4. Exiting a program
    By osal in forum Windows Programming
    Replies: 2
    Last Post: 07-14-2004, 08:51 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM

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