#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node *next;
};
struct node *push(struct node *head, int x)
{
struct node *v = (struct node *)malloc(sizeof(struct node *));
v->next = head;
v->value = x;
return v;
}
struct node *pop(struct node *head)
{
return head->next;
}
void print(struct node *head)
{
if (head == NULL)
{
printf("NULL\n");
}
else
{
while (head != NULL)
{
printf("%d", head->value);
if (head->next != NULL)
{
printf(" ");
}
head = head->next;
}
printf("\n");
}
}
int main()
{
struct node *head = NULL;
char c;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i )
{
scanf(" %c ", &c);
if (c == 'a')
{
int x;
scanf("%d", &x);
head = push(head, x);
print(head);
}
else if (c == 'd')
{
head = pop(head);
print(head);
}
}
}
在上面的代碼中,當字符輸入為 'a' 時,我采用整數輸入,但當字符輸入為 'd' 時,我不必接受輸入,因為我正在洗掉堆疊的第一個元素。我提到了這個帖子。但是現在我無法處理“d”的情況,我不必再次輸入整數。請糾正我的代碼。
編輯:
正如對我的查詢的回復中提到的,如果我從 %c 中洗掉空格,那么我的代碼中提到的 'a' 和 'd' 可以正常作業,但是 for 回圈不會運行 4 次,而是只運行 2 次。因此輸入 I 和輸出如下:
4
a 1
1
d
NULL
Here, (4,a 1,d) are inputs and (1 and NULL) outputs. After printing NULL the program terminates but ideally, it should have taken two more inputs. Please rectify my code.
uj5u.com熱心網友回復:
問題是scanf格式中的尾隨空格。當scanf格式包含空格時, scanf 將讀取(并丟棄)空白字符,直到它獲得非空白字符(此時它將將該非空白字符保留為下一個模式或呼叫要讀取的下一個字符) .
這樣做的最終結果是,當您有像 一樣的輸入行時dEnter,scanf(" %c ",呼叫不會回傳,直到您輸入另一行帶有一些非空白字符的行(這些字符將留給下一次 scanf 呼叫讀取)。
只需洗掉格式中的那些尾隨空格,一切都應該沒問題。的領先空間是必要的,忽略任何空白(從前述命令這樣的新行)之前的命令字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341524.html
標籤:c
上一篇:從指標中提取字符陣列長度的問題
