#问题:为什么对于存a,b,c三个成员,输出的a成员末尾包含b成员的开头字符
比如输入:3310120150912233 2 4,实际输出a为33101201509122332
问题代码:
成员:
输入代码:
#include<stdio.h> #include<math.h> #include<string.h> struct student{ char a[16]; char b[2]; char c[2]; struct student *next; }*p,*head,*end,*h; struct num{ char d[2]; struct num *next; }*p2,*head2,*end2,*h2; void main(){ int N,n,i; scanf("%d",&N); head=(struct student*)malloc(sizeof(struct student)); end=head; for(i=0;i<N;i++) { p=(struct student*)malloc(sizeof(struct student)); scanf("%s",p->a); scanf("%s",p->b); scanf("%s",p->c); end->next=p; end=p; } end->next=NULL; scanf("%d",&n); head2=(struct num*)malloc(sizeof(struct num)); end2=head2; for(i=0;i<n;i++) { p2=(struct num*)malloc(sizeof(struct num)); scanf("%s",p2->d); end2->next=p2; end2=p2; } end2->next=NULL; h2=head2; while(h2->next!=NULL) { h2=h2->next; h=head; while(h->next!=NULL) { h=h->next; if(strcmp(h2->d,h->b)==0) { printf("%s %s\n",h->a,h->c); break; } } } }
char a[16];最大只能存储15个字符,因为结尾还有一个\0呢
其实稍微大一些也没事,可以大不可以小。建议 char a[20], b[10], c[10];
【以下回答由 GPT 生成】
这个问题是因为字符串数组没有正确的终止符导致的。在C语言中,字符串必须以空字符'\0'结尾作为字符串的终止符。而你的代码中没有明确给字符串数组的最后一个元素赋值为'\0',导致字符串没有正确的终止。
为了解决这个问题,你需要在读取字符串之后,手动添加空字符'\0'到字符串数组的末尾。下面是修改后的代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
struct student{
char a[16];
char b[2];
char c[2];
struct student *next;
}*p,*head,*end,*h;
struct num{
char d[2];
struct num *next;
}*p2,*head2,*end2,*h2;
int main(){
int N,n,i;
scanf("%d",&N);
head=(struct student*)malloc(sizeof(struct student));
end=head;
for(i=0;i<N;i++){
p=(struct student*)malloc(sizeof(struct student));
scanf("%15s",p->a);
scanf("%1s",p->b);
scanf("%1s",p->c);
p->a[15] = '\0'; // 添加空字符终止符
p->b[1] = '\0'; // 添加空字符终止符
p->c[1] = '\0'; // 添加空字符终止符
end->next=p;
end=p;
}
end->next=NULL;
scanf("%d",&n);
head2=(struct num*)malloc(sizeof(struct num));
end2=head2;
for(i=0;i<n;i++){
p2=(struct num*)malloc(sizeof(struct num));
scanf("%1s",p2->d);
p2->d[1] = '\0'; // 添加空字符终止符
end2->next=p2;
end2=p2;
}
end2->next=NULL;
h2=head2;
while(h2->next!=NULL){
h2=h2->next;
h=head;
while(h->next!=NULL){
h=h->next;
if(strcmp(h2->d,h->b)==0){
printf("%s %s\n",h->a,h->c);
break;
}
}
}
return 0;
}
通过在每个字符串数组最后添加空字符终止符,你可以确保每个字符串都以正确的方式终止,解决了输出结果错误的问题。
【相关推荐】