代码不会在 C 中的 do while 循环中执行

标签 c do-while

这是我的代码片段:

printf("\nCommand? ");
ret = scanf("%c", &command);
do
{
    // printf("Command? ");
    // ret = scanf("%c", &command);
    if (ret != 1)
    {
        fprintf(stderr, "Invalid input!\n");
    }

    if (command == 'd')
    {
        result = dequeue(&queue1, &entry);
        if (result == 1)
            printf("%d was dequeued\n", entry);
        else if (result == 0)
            fprintf(stderr, "ERROR: attempt to dequeue from an empty"
                    " queue\n");
    }
    else if (command == 'e')
    {
        ret = scanf("%d", &add);
        result = enqueue(q, add);
    }
    else if (command == 'q')
        break;
    else
        fprintf(stderr, "Invalid command!\n");

    printf("Queue:");
    for (int i = 0; i < q->end; ++i)
    {
        printf("%d", q->element[i]);
    }
    printf("\nCommand? ");
    scanf("%c", &command);
} while (command != 'q');

下面是部分GDB日志:

146             printf("Command? ");
(gdb)
147             ret = scanf("%c", &command);
(gdb)
Command? d
148             if (ret != 1)
(gdb)
153             if (command == 'd')
(gdb)
155                 result = dequeue(&queue1, &entry);
(gdb)
156                 if (result == 1)
(gdb)
158                 else if (result == 0)
(gdb)
159                     fprintf(stderr, "ERROR: attempt to dequeue from an empty"
(gdb)
ERROR: attempt to dequeue from an empty queue
172             printf("Queue:");
(gdb)
173             for (int i = 0; i < q->end; ++i)
(gdb)
177             printf("\nCommand? ");
(gdb)
Queue:
178             scanf("%c", &command);
(gdb)
179         } while (command != 'q');
(gdb)

如您所见,第 172 行 printf("Queue:"); 以及其余代码都不会执行。我不明白为什么。

我在命令中输入了d

有人能帮我解释一下吗?谢谢。

最佳答案

我认为您担心的是 printf 在调试器中被跟踪但没有产生输出。这可能是因为 printf 调用将输出发送到 stdout,这通常是缓冲的,因此在 gdb 中运行时输出可能直到稍后才会出现。在某些系统中,缓冲区会在看到换行符时刷新。因此,您可以尝试将 \n 添加到 "Queue:" 的末尾。或者 fflush(stdout); 打印后肯定会导致 printf 工作。 stderr 的输出没有缓冲。这就是为什么您会立即看到该输出的原因。

关于代码不会在 C 中的 do while 循环中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519359/

相关文章:

c - 2D 和 3D 数组的动态分配/解除分配

c - 为什么我的 yacc 规则不能在这里减少?

java - 在 do while 循环中尝试 catch

c++ - 为什么不能在 do while 循环的表达式部分声明变量?

C do while 循环在检查条件之前重复 2 次

c - 得到 "error: expected identifier or ' ('"

c++ - 通过将 "goto"转换为分支进行优化

c - C 中的文件处理。更多命令?

尝试在 xcode 中退出程序时出现 C++ 11db 错误。初学者级

java - 无法得到一段时间,或者做... while 循环工作,查找了多个答案。没有任何效果