【发布时间】:2014-03-14 02:46:49
【问题描述】:
我想在不使用c库函数的情况下计算字符串的长度并将字符串复制到另一个,但是当我使用fgets()函数从键盘读取字符串时,代码没有显示长度的实际值以及目标字符串。我使用fgets() 函数而不是gets(),因为编译器说gets()function 已“弃用”。但是当我将代码中的sizeof(source) 更改为整数值时,假设50 代码工作正常。谁能告诉我这段代码有什么问题以及为什么编译器说gets() 函数已被弃用。
这是代码:
#include <stdio.h>
#include <stdlib.h>
int len(char *source);
char *coppy(char *dest,char *source);
int main (void){
char *source,*dest;
source=(char *)malloc(len(source)+1);
printf("enter string:");
fgets(source,sizeof(source),stdin);
if(source[len(source)-1]=='\n'){
source[len(source)-1]='\0';
}
dest=(char *)malloc(len(source)+1);
coppy(dest,source);
printf("dest=%s\n",dest);
printf("length source=%d\n",len(source));
printf("length dest=%d\n",len(dest));
return 0;
}
int len(char *source){
int i=0;
while(*source!='\0'){
source++;
i++;
}
return i;
}
char *coppy(char *dest,char *source){
while(*source!='\0'){
*dest=*source;
source++;
dest++;
}
*dest='\0';
return dest;
}
这是运行该代码时的结果:
enter string:programming dest=pro length source=3 length dest=3
【问题讨论】:
-
更正:
fgets()已经工作了几十年。使用fgets的您的代码不起作用。