如题所述
其实核心就是实现动态数组,无论字符串多长,都能够储存。
用getchar一个一个得到字符,直到文件结束。
核心代码实现:
char * s2 = NULL,s1 = (char *)malloc(100); //初始化字符串空间
if (s1 == NULL) return; //内存分配失败,返回
while((c=getchar())!=EOF){ //判断是否到文件结束,一个个读取字符
if(k<=n){ //当前字符串长度大于等于字符串空间长度时
k*=2; //长度增长2倍
s2 = (char *)realloc(s1,k); //重新分配内存
if(s2 == NULL){ //内存分配失败
free(s1); //释放已分配内存
return;
}else{ //内存分配成功
s1=s2;
}
}
s1[n++]=c; //字符串赋值字符
}
s1[n]=0; //字符串末尾置为\0
温馨提示:答案为网友推荐,仅供参考
第1个回答 2010-10-25
用string类就基本满足你的要求了,自动完成字符串的内存分配和变长
最大支持1073741820长度的字符串。
最大支持1073741820长度的字符串。
第2个回答 推荐于2017-09-11
#include conio.h
#include stdio.h
#include stdlib.h
#include string.h
#define GRAW_LENGTH 50
void AppendChar(char* pBuf, int nBufLen, char ch)
{
int nOldLen = pBuf ? (int)_mbstrlen(pBuf) : 0;
if (nOldLen + 2 nBufLen)
{
char* pNewBuf = (char*)malloc(nOldLen + GRAW_LENGTH);
memset(pNewBuf, 0, nOldLen + GRAW_LENGTH);
if (pBuf)
{
memcpy(pNewBuf, pBuf, nOldLen + 1);
free(pBuf);
}
pBuf = pNewBuf;
}
pBuf[nOldLen] = ch;
}
int main(int argc, char* argv[])
{
char ch;
char* pBuf = 0;
int nLen = 0;
do
{
ch = getch();
printf("%c", ch);
AppendChar(pBuf, nLen, ch);
} while (ch != 13);
printf("\n%s\n", pBuf);
if (pBuf) free(pBuf);
return 0;
}本回答被提问者采纳
#include stdio.h
#include stdlib.h
#include string.h
#define GRAW_LENGTH 50
void AppendChar(char* pBuf, int nBufLen, char ch)
{
int nOldLen = pBuf ? (int)_mbstrlen(pBuf) : 0;
if (nOldLen + 2 nBufLen)
{
char* pNewBuf = (char*)malloc(nOldLen + GRAW_LENGTH);
memset(pNewBuf, 0, nOldLen + GRAW_LENGTH);
if (pBuf)
{
memcpy(pNewBuf, pBuf, nOldLen + 1);
free(pBuf);
}
pBuf = pNewBuf;
}
pBuf[nOldLen] = ch;
}
int main(int argc, char* argv[])
{
char ch;
char* pBuf = 0;
int nLen = 0;
do
{
ch = getch();
printf("%c", ch);
AppendChar(pBuf, nLen, ch);
} while (ch != 13);
printf("\n%s\n", pBuf);
if (pBuf) free(pBuf);
return 0;
}本回答被提问者采纳
第3个回答 2010-10-25
内存有限制的,不管什么语言都不可能无限长度。
在C语言中可以做到动态的,先预分配一定得字符空间,不够用时再扩充
char* buf = malloc(1024);
不够用则扩大,原先的值不会被破坏
buf = realloc(2 * 1024);
在C语言中可以做到动态的,先预分配一定得字符空间,不够用时再扩充
char* buf = malloc(1024);
不够用则扩大,原先的值不会被破坏
buf = realloc(2 * 1024);
第4个回答 2010-10-25
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *pszBuff = NULL;
int a;
printf("输入字符串长度:");
scanf("%d", &a);
pszBuff = (char *)malloc(sizeof(char) * a);
if (!pszBuff)
exit(1);
printf("输入字符串:");
scanf("%s", pszBuff);
printf("%s\n", pszBuff);
free(pszBuff);
return 0;
}
#include <stdlib.h>
int main(void)
{
char *pszBuff = NULL;
int a;
printf("输入字符串长度:");
scanf("%d", &a);
pszBuff = (char *)malloc(sizeof(char) * a);
if (!pszBuff)
exit(1);
printf("输入字符串:");
scanf("%s", pszBuff);
printf("%s\n", pszBuff);
free(pszBuff);
return 0;
}