這裏是我的代碼片段:代碼將不會執行在做while循環用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進入命令
有人能幫助我解釋一下嗎?謝謝。
呃......因爲你之前打破了循環?無論如何,代碼是混亂的。它應該變得更簡單,更清晰,更不容易出錯。即使它工作。 –
我在'command *'中鍵入'd',而不是'q'。 – hlx98007
你確定print語句沒有執行嗎?我猜想q是null,你的問題是q-> end。由於I/O刷新問題,您不會看到printf。嘗試把fflush(stdout);在你的printf之後 –