“任意长度”实际上是做不到的,即使所用的软件平台没有限制,硬件环境也不允许。所以“任意长度”应当理解为在一个很大的空间之内没有限制地输入字符串而不用事先确定长度。鉴于这种理解,可以定义一个输入函数,先动态申请一个较大的空间,直接向其内输入字符串;输入完毕后检测其长度,再按实际需要申请一个合适大小的空间,把刚才输入的字符串拷贝到这个合适大小的空间里,再把原先申请的大空间释放。举例代码如下:
//#include "stdafx.h"//If the vc++6.0, with this line.
#include "
stdio.h"
#include "
string.h"
#include "
stdlib.h"
#define N 131071
char *Any_Long_Str(char *p){
char *pt;
if((pt=(char *)malloc(N))==NULL){//Apply for a larger space for temporary use
printf("Apply for temporary use of space to fail...\n");
exit(0);
}
gets(pt);//Get a string from the keyboard
if((p=(char *)malloc(strlen(pt)+1))==NULL){//Apply for a suitable size of space
printf("Application memory failure...\n");
exit(0);
}
strcpy(p,pt);//Copy the string pt to p
free(pt);//Release the temporary use of space
return p;
}
int main(void){
char *pstr=NULL;
printf("Input a string:\n");
pstr=Any_Long_Str(pstr);
printf("%s\n",pstr);//Look at...
free(pstr);//Release the space
return 0;
}