1

I am trying to make my program run only while the user enters Y or y but it only runs once, and even if it isn't Y or y. Input will either be Y, y, N or n

printf("Welcome to the Jumble Puzzle Solver!\n\n");
printf("Would you like to enter a jumbled word?\n");
scanf("%s", &answer);


    do{

    printf("What word would you like scored?\n");
    scanf("%s", &letters);

    strcpy(changeletters, letters);

    recursivepermute(letters, changeletters, checkword, k, dictionary ,max, min);

    printf("Would you like to enter a jumbled word?\n");
    scanf("%s", &answer);

    }while (answer == 'Y' || answer == 'y');
pb2q
  • 58,613
  • 19
  • 146
  • 147
Ryan
  • 57
  • 3
  • 11
  • 2
    What type is `answer`? Also, the homework tag is deprecated. – chris Oct 12 '12 at 23:54
  • possible duplicate of [Test loops at the top or bottom? (while vs. do while)](http://stackoverflow.com/questions/224059/test-loops-at-the-top-or-bottom-while-vs-do-while) – alk Oct 13 '12 at 12:17

2 Answers2

1

do { } while() causes the body to always be executed at least once. If you want the condition checked first, just use while:

// If answer is:
// char answer;

scanf("%c", &answer);
while (answer == 'Y' || answer == 'y')
{
     printf("What word would you like scored?\n");
    // ...

    scanf("%c", &answer);
}

You also need to use scanf("%c" if answer is a char. The %s is to scan a string of characters (ie: char[20]), and would need to be checked differently, using a method like strcmp or similar.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Ok the do while explanation makes a lot of sense. I changed it t %c and made the while loop like this, but even if I enter Y or y it still ends the program. – Ryan Oct 13 '12 at 00:04
  • @Ryan Check what you're getting in `answer` in a debugger. Is it 'Y' or 'y'? How is `answer` declared? – Reed Copsey Oct 13 '12 at 00:05
  • Ah figured out my problem. Still had it declared as char answer[2] instead of just char answer. Thank you for all the help! – Ryan Oct 13 '12 at 00:08
  • @Ryan With a string, you could use `strcmp` to do the check instead of checking against a single character. – Reed Copsey Oct 13 '12 at 00:08
0

if you want the user to play the game once and then be asked about playing again then the use of do-while loop is more appropriate. But if you want to give the user the option Not to play the game at all then use the while loop

yohannist
  • 4,166
  • 3
  • 35
  • 58