用C編寫這個程序。使用兩個堆棧實現隊列(CTCI中的問題3.5)。通過推送和彈出對scanf的不同期望
我想讓用戶輸入「push {integer}」或「pop」。我正在使用scanf("%s %d", op, &data);
但是,這會導致程序中的行爲不一致,其中用戶輸入「push {integer}」正常工作,但用戶輸入「pop」會導致程序執行延遲。似乎scanf("%s %d", op, &data);
等待一些輸入到&數據,但我希望它只接受「流行」沒有任何數據。
代碼:
#include "stdio.h"
#include "stdlib.h"
#include "../Chapter-2/linkedlist.h"
#include "string.h"
int main(int argc, char *argv[])
{
char op[10];
int data;
struct node *pushStack = NULL;
struct node *popStack = NULL;
printf("Usage: \"push\" some_int ||OR|| \"pop\"\n");
while(1)
{
scanf("%s %d", op, &data);
if(strncmp(op, "push", 4) == 0)
{
if(pushStack == NULL)
{
if(popStack != NULL) //we were popping from the "queue" so we need to switch to pushing mode
{
while(popStack != NULL) //transfer all from popstack to pushstack
{
push(&pushStack, pop(&popStack));
}
}
}
push(&pushStack, data);
} else if(strncmp(op, "pop", 3) == 0)
{
if(popStack == NULL)
{
if(pushStack != NULL) //we were pushing to "queue" so we need to switch to pop mode
{
while(pushStack != NULL) // transfer all from pushStack to popStack
{
push(&popStack, pop(&pushStack));
}
}
}
if(popStack == NULL) //could still be null if there was nothing to transfer from pushstack
printf("Queue is empty. You have nothing to pop.\n");
else
printf("Popped queue: %d\n", pop(&popStack));
} else {
printf("Invalid usage.\n");
printf("Usage: \"push\" some_int ||OR|| \"pop\"\n");
}
}
return 0;
}
我建議你用'fgets'獲取輸入。然後應用'sscanf'並檢查返回值(轉換字段的數量,在所有**情況下的*必需*測試)。如果收到「pop」,沒有第二個參數,你可以更容易地轉儲輸入字符串,而不是忽略不滿意的'scanf'格式字段,它們是持久的。與'scanf'不同,字符串函數'sscanf'不等待更多信息。 –
另外:標準庫頭文件應該包含在'while #include <#include中,while'(1!= scanf(「%9s」,op))''while''include #include <#include> stdio.h'' –