【问题标题】:do while statement executing only twice code::block and dev c++do while 语句只执行两次 code::block 和 dev c++
【发布时间】:2015-11-16 02:44:17
【问题描述】:

大家好,附上我正在使用的简单代码:

#include <stdio.h>

void main()
{char choice;
    do
    {
        printf("\nHello World");
        printf("\nDo you wish to continue:\n");
        choice = getchar();
    }
    while(choice=='y');
}

在执行时我得到以下输出:

Hello World
Do you wish to continue
y

Hello World
Do you wish to continue
--------------------End of Program--------------------

如你所见, getchar() 函数在第二次迭代中不起作用。 更重要的是,程序没有等我在第二次迭代中输入“选择”。

出了什么问题?

【问题讨论】:

  • 补充其他人所说的,c 应该是int

标签: c while-loop codeblocks dev-c++ getchar


【解决方案1】:

输入y后,你按下enter键作为第二个输入。所以程序终止,因为第二个选择不是y而是它的\n..你可以使用这个

do
{
    printf("\nHello World");
    printf("\nDo you wish to continue:\n");
    choice = getchar();
    getchar();
}

第二个 getchar() 自动将\n 作为输入并跳过它

【讨论】:

    【解决方案2】:

    在第一次输入后您将按下的“Enter”键停留在缓冲区中,并在下次控制到达getchar() 时被读取。 为避免这种情况,您可以在第一个 getchar() 之后使用另一个 getchar(),它将吸收输入的换行符。或者你可以使用这个

    if(c != '\n') c=getchar();

    【讨论】:

      【解决方案3】:

      在 y 之后按“enter”,然后对于下一个 getchar(),将 enter 作为输入。您可以刷新或使用两个 getchar 并仅考虑第一个输入 例如:c=getchar(); d=getchar();

      在while中检查c

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-10
        • 1970-01-01
        • 2020-05-07
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 2016-04-18
        相关资源
        最近更新 更多