C help... why is my loop running twice?

Posted:
in Genius Bar edited January 2014
I've got the following code as part of my [for school] program:



[code]while (reply != 'n') { /* outer loop start */



/* use randNum to copy a random word into variable *word[] */

x = randNum(nw);

*word = wordArray[x];

printf("\

x: %d\

*word: %s\

wordArray[%d]: %s\

\

", x, *word, x, wordArray[x]);



/* */





/* determine whether to continue */

printf("Play again? (y/n): ");

scanf("%c", &reply);

}</pre><hr></blockquote>



Everytime I run it I get something like the following: [quote][Zeta-Reticuli:~/hangman] iceman% ./hangman



x: 46

*word: weather

wordArray[46]: weather



Play again? (y/n): y



x: 21

*word: guitar

wordArray[21]: guitar



Play again? (y/n):

x: 21

*word: guitar

wordArray[21]: guitar



Play again? (y/n): y



x: 23

*word: inquisitive

wordArray[23]: inquisitive



Play again? (y/n):

x: 23

*word: inquisitive

wordArray[23]: inquisitive



Play again? (y/n): y



x: 24

*word: kitchen

wordArray[24]: kitchen



Play again? (y/n):

x: 24

*word: kitchen

wordArray[24]: kitchen



Play again? (y/n): n

<hr></blockquote>

Everything after the first run gets outputted twice... anyone know anything to help?

Comments

  • Reply 1 of 3
    change your scanf line to this:

    [code]scanf("%c\

    ", &reply);</pre><hr></blockquote>



    scanf pulls off the enter [new line] character, right after you input something. for instance, you hit "23[enter]", it pulls 23, and uses that. next go around, it pulls [enter] ("\

    "), and uses that. putting the "\

    " at the end of the scanf rip forces scanf pull it off the buffer, and drop it.
  • Reply 2 of 3
    Well that works but then I have to type a response, hit enter, then do it again before it continues the loop...



    never had this problem before.
  • Reply 3 of 3
    I just changed my scanf to the following by accident and it works:

    [code]scanf(" %c", &reply);</pre><hr></blockquote>

    Notice the space before %c... now why does this work?
Sign In or Register to comment.