关于链表的字符输入输出疑惑
本意是想先输入一个数字表示字符串长度,再输入字符串,将字符串内的字符依次输出#include <stdio.h>
#include <stdlib.h>
struct node
{
char zf;
struct node *next;
};
int main()
{
int n;
scanf("%d",&n);
struct node *head,*rear,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
rear=head;
for(int i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%c",&p->zf);
rear->next=p;
rear=p;
}
rear->next=NULL;
p=head->next;
while(p)
{
printf("%c ",p->zf);
p=p->next;
}
}
运行之后假设输入“4asdf”输出的结果是“ a s d”
但是将结构体中的char类型换成int类型之后输入“4 1 2 3 4”输出的结果是“1 2 3 4” 你的代码,看看这句 printf("%c ",p->zf);
#include <stdio.h>
#include <stdlib.h>
struct node
{
char zf;
struct node *next;
};
int main()
{
int n;
scanf("%d",&n);
getchar(); // 忽略空格
struct node *head, *p, *tmp;
for(int i=0; i<n; i++)
{
tmp=(struct node*)malloc(sizeof(struct node));
tmp->next=NULL;
scanf("%c",&tmp->zf);
// 保存头指针
if(i==0) {
p = tmp;
head = tmp;
continue;
}
// 交换指针
p->next=tmp;
p=tmp;
}
p=head;
while(p)
{
printf("%c",p->zf);
p=p->next;
}
return 0;
}
应该是第一次取n的时候,缓冲区里还有一个回车符
可以用 getchar() 吃掉回车符
#include <stdio.h>
#include <stdlib.h>
struct node
{
char zf;
struct node *next;
};
int main()
{
int n;
scanf("%d",&n);
getchar();
struct node *head,*rear,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
rear=head;
for(int i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%c",&p->zf);
rear->next=p;
rear=p;
}
rear->next=NULL;
p=head->next;
while(p)
{
printf("%c ",p->zf);
p=p->next;
}
}
页:
[1]