这是我的代码片段:
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)
如您所见,行172printf("Queue:");
和其他代码将不被执行。我不知道为什么。
我在命令中输入d
有人可以帮我解释一下吗?谢谢。
全部。
我想我已经弄清楚了怎么做:只是编写另一个函数以打印出所有结果。
所以修改后的代码是这样的:
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不相关。
谢谢大家的建议。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句