#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main()
{
int n = 0;
while (scanf("%d", &n) != EOF)
{
char c1[16] = { 0 };
char c2[16] = { 0 };
char l[16] = { 0 };
char* sa = (char*)calloc(1, 16*n);
scanf("%s", l);
int cnt = 0;
for (int i = 0; i < n; i++)
{
scanf("%s", c1);
scanf("%s", c2);
if (!strcmp(l, c2))
{
strcat(sa + strlen(sa), c1);
sa[strlen(sa)] = '\n';
cnt++;
}
memset(c1, 0, 16);
memset(c2, 0, 16);
}
printf("%s", sa);
printf("%d", cnt);
free(sa);
}
return 0;
}
没有提示错误信息,只显示不通过
地址字符串长度应该设置21,你怎么是16
你题目的解答代码如下:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main()
{
int n = 0;
while (scanf("%d", &n) != EOF)
{
char c1[100] = { 0 }; //题目没说姓名长度是多少,可以设置长一些
char c2[21] = { 0 }; //地址字符串长度应该设置21
char l[21] = { 0 }; //地址字符串长度应该设置21
char* sa = (char*)calloc(1, 100*n);
scanf("%s", l);
int cnt = 0;
for (int i = 0; i < n; i++)
{
scanf("%s", c1);
scanf("%s", c2);
if (!strcmp(l, c2))
{
strcat(sa + strlen(sa), c1);
sa[strlen(sa)] = '\n';
cnt++;
}
memset(c1, 0, 100);
memset(c2, 0, 21);
}
printf("%s", sa);
printf("%d", cnt);
free(sa);
}
return 0;
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
改这样试试:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main()
{
int n = 0, cnt;
char c1[100], c2[21], l[21], *sa;
while(scanf("%d",&n)==1 && (getchar()) != EOF)
{
if (n < 1 || n > 100)
{
//printf("Input error.\n");
continue;
}
cnt = 0;
memset(c1,0,100);
memset(c2,0,21);
memset(l, 0,21);
sa = (char*)calloc(1, 100*n);
scanf("%s", l);
while (n--)
{
scanf("%s %s", c1, c2);
if (!strcmp(l, c2))
{
strcat(sa + strlen(sa), c1);
sa[strlen(sa)] = '\n';
cnt++;
}
}
printf("%s", sa);
printf("%d\n", cnt);
free(sa);
}
return 0;
}