簡體   English   中英

代碼不會在C中的do while循環中執行

[英]Code won't execute in do while loop in C

這是我的代碼片段:

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未緩沖。 這就是為什么您立即看到該輸出的原因。

正如您在調試器中單步執行代碼所看到的那樣,它已執行。 它不會立即打印,因為printf()輸出一直保存在緩沖區中,直到緩沖區已滿或遇到換行符為止。 如果您需要立即查看輸出,則在末尾添加換行符,或者在之后fflush(stdout)替換。

檢查完代碼后,我唯一能想到的解決方案是for循環q->end是<= 0

所有。

我想我已經弄清楚了怎么做:只是編寫另一個函數以打印出所有結果。

所以修改后的代碼是這樣的:

do
{
    ret = fgets(buf, BUF_LENGTH, "%c %d", &command, &add);
    if (ret != 1 && ret != 2)
    {
        fprintf(stderr, "Invalid input!\n");
        continue;
    }

    if (command == 'd')
    {
        ...
    }
    else if (command == 'e')
    {
         ...
    }
    else if (command == 'q')
        break;
    else
        fprintf(stderr, "Invalid command!\n");

    /* Printing out the queue elements */
    print_element(q);

    printf("Command? ");
} while (command != 'q');

我知道我的代碼很亂,我仍然是C編程語言的初學者。 我正在學習指針。

代碼的“ ...”部分進行了一些修改,但我相信這些更改與I / O不相關。

謝謝大家的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM