c - 循环问题,while循环执行额外的迭代

标签 c while-loop

<分区>

程序:

#include <stdio.h>
int main() {
    char t;
    while(1) {
        t='\0';
        printf("\nExit?(y/n): ");
        scanf("%c", &t);
        if( t=='y' || t=='Y') {
            return 0;
        }
        else
        printf("\nContinuing...");
    }
    return 0;
}

输出:

$ vim Return.c
$ gcc -o Return Return.c
$ ./Return

Exit?(y/n): n

Continuing...
Exit?(y/n):
Continuing...
Exit?(y/n): n

Continuing...
Exit?(y/n):
Continuing...
Exit?(y/n): y
$

在将 'n' 作为输入后,

Continuing...
Exit?(y/n):

再循环一次,不接受用户的输入。如果代码有任何错误,请告诉我

最佳答案

您需要确保 scanf 丢弃换行符。像这样尝试:

scanf(" %c", &t);

关于c - 循环问题,while循环执行额外的迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22006759/

相关文章:

C帮助批处理使用系统功能

r - 如何计算条件的 TRUE 值,直到在 R 中找到 FALSE

Linux - sleep 自动重启

c++ - 使用 while/do-while 循环进行数组元素设置

javascript - 后循环中的 JQuery onclick 函数错误

c - 为什么乘法后要进行自增运算?

c - const char* 应该在 C 中释放吗?

c++ - C++ 的箭头 (->) 运算符的正式名称是什么?

JavaScript while循环计算

c - 是什么导致数组中的 float 舍入?