【问题标题】:Do While or while?做While还是while?
【发布时间】:2012-10-12 23:53:38
【问题描述】:

我试图让我的程序仅在用户输入 Y 或 y 时运行,但它只运行一次,即使它不是 Y 或 y。输入将是 Y、y、N 或 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');

【问题讨论】:

标签: c loops while-loop do-while


【解决方案1】:

do { } while() 导致主体总是被执行至少一次。如果要先检查条件,只需使用 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);
}

如果answerchar,您还需要使用scanf("%c"%s 用于扫描字符串(即:char[20]),需要进行不同的检查,使用类似strcmp 或类似的方法。

【讨论】:

  • 好吧,虽然解释很有意义。我将它更改为 t %c 并像这样进行了 while 循环,但即使我输入 Y 或 y 它仍然会结束程序。
  • @Ryan 在调试器中检查answer 中的内容。是'Y'还是'y'? answer 是如何声明的?
  • 啊,我发现了我的问题。仍然将其声明为 char answer[2] 而不仅仅是 char 答案。谢谢大家的帮助!
  • @Ryan 对于字符串,您可以使用strcmp 进行检查,而不是检查单个字符。
【解决方案2】:

如果您希望用户玩一次游戏然后被询问是否再次玩,那么使用do-while 循环更合适。但是如果你想让用户选择根本不玩游戏,那么请使用while 循环

【讨论】:

  • 谢谢你解释了很多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
  • 2013-01-12
  • 2017-06-05
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 2011-10-20
相关资源
最近更新 更多