匿名用户
1级
2011-07-06 回答
首先,C必然定义为字符数组,C语言没有定义字符串的关键字,C语言用字符数组处理字符串。如果需要动态长度字符串必须用字符指针实现。我写了一个类似的程序。
#include
#include
#include
int main(void) {
const int SIZE_INC=16;
char *a="abcd";
char *b="bcdef";
char *astr, *cptr;
char ch, ich;
int csize=0, cread=0;
// 读入未知长度字符串,以回车或者EOF结束
printf("Input a string:\n");
cptr = astr = (char *)malloc(SIZE_INC);
csize = SIZE_INC;
ich = getchar();
for (;;) {
if (ich == '\n' || ich == EOF)
ch = '\0';
else
ch = ich;
if (cread == csize) {
astr = (char *)realloc(astr, csize + SIZE_INC);
csize += SIZE_INC;
cptr = astr + cread;
}
*cptr = ch;
if (ch == '\0') break;
cread++; cptr++;
ich = getchar();
}
if (!strcmp(astr,a))
printf("The string you input equals string a.\n");
else if (!strcmp(astr,b))
printf("The string you input equals string b.\n");
else
printf("Your string is: %s\n",astr);
system("pause");
return 0;
}
另外,团IDC网上有许多产品团购,便宜有口碑