求解一个分开姓和名的函数问题

by1945 2007-09-05 04:12:29
题目:通过输入姓名,比如"michael jordan",写个函数实现
the first name:michael
the last name:jordan
要求用函数;
void split(char MyName[])
{
int i,j=0;
char test[100],test1[100];
while(MyName[i]!=' ')
{
test[i]=MyName[i];
i++;
}
printf("the first name is:%s",test);
j=i;
while(MyName[i]!='\0')
{
test1[i-j]=MyName[i];
i++;
}
printf("the last name is:%s",test1);
}
main()
{
split(michael jordan);
split(John Doe);
}
我写了之后,发现执行第一个没有问题,执行到第二句split(a b)的时候会保留之前一句里面的内容,也就是函数里面的数组没有执行清除操作,该怎么做,谢谢!
...全文
133 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
by1945 2007-09-06
  • 打赏
  • 举报
回复
谢谢,我试下
BHLT_US 2007-09-05
  • 打赏
  • 举报
回复
可以通过清空来解决问题,但是
memset(test,0,sizeof(test));
不是很准确,sizeof(test)= 4 * 100 = 400 bytes.
我们的目的是对以test 为首的100个字节赋值为0吧。
bzero(test,100);
可以满足需求
HW121 2007-09-05
  • 打赏
  • 举报
回复
test,test1不用清空,在循环之后加test[i] = '\0';test[i-j]='\0';即可
cceczjxy 2007-09-05
  • 打赏
  • 举报
回复
void split(char MyName[])
{
int i=0,j=0; //初值
char test[100],test1[100];
memset(test,0,sizeof(test)); //清空
memset(test1,0,sizeof(test1));
while(MyName[i]!=' ')
{
test[i]=MyName[i];
i++;
}
printf("the first name is:%s\n",test);
j=i;
while(MyName[i]!='\0')
{
test1[i-j]=MyName[i];
i++;
}
printf("the last name is:%s\n",test1);
}

int main()
{
split("michael jordan");
split("John Doe");
}
~

69,364

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧