读书人

C语言录入无限制长度字符串?该如何解决

发布时间: 2012-03-22 17:43:57 作者: rapoo

C语言录入无限制长度字符串?
目是入限制字符放在一字符串, 并入了多少小字母.
可是我的每次都是到第100字符的候就不能再入了, 教一下是哪有..

以下我的代:

C/C++ code
/*Written by Kai C. Sept. 16, 2008*//*Edited on Nov. 2, 2008*//*Email:ck.nonamestudio@gmail.com*/#include <stdio.h>void main(void){    char* str;    char* tmpStr;    int i = 0, sum = 0, n = 0;    str = malloc(5);    printf("Enter a string (don't mind the lenth):\n");    do    {        /*re-allocate memory*/        if(n % 5 == 0 && n != 0)        {            tmpStr = malloc(n);            for(i = 0; i <= n; i++)            {                tmpStr[i] = str[i];            }            /*str = realloc(n + 5, sizeof(char));*/            free(str);            str = malloc(n + 5);            for(i = 0; i <= n; i++)            {                str[i] = tmpStr[i];            }            free(tmpStr);        }        scanf("%c", &str[n]);    }while(str[n++] != '\n');    /*c-string terminated by Null character*/    str[n - 1] = '\0';    printf("The string you just entered is:%s\n", str);    i = 0;    while(str[i])    {        if(str[i] >= 'a' && str[i] <= 'z')        {            sum++;        }        i++;    }    printf("You entered %d small letters.\n", sum);    free(str);}




[解决办法]
#include <malloc.h>是很好的习惯
[解决办法]
录入无限 如果是我 我就用链表

struct test
{
char ch;
struct test *next;
}
[解决办法]
#include <stdio.h>
#include<malloc.h>////////////////
void main(void)
{
char* str;
char* tmpStr;
int i = 0, sum = 0, n = 0;

str =(char *)malloc(5);//////////////////////////////////

printf("Enter a string (don't mind the lenth):\n");

do
{
/*re-allocate memory*/
if(n % 5 == 0 && n != 0)
{
tmpStr =(char *) malloc(n);/////////////////////////////////
for(i = 0; i <= n; i++)
{
tmpStr[i] = str[i];
}

/*str = realloc(n + 5, sizeof(char));*/
free(str);
str = (char *)malloc(n + 5);////////////////////////////////////

for(i = 0; i <= n; i++)
{
str[i] = tmpStr[i];
}

free(tmpStr);
}

scanf("%c", &str[n]);
}while(str[n++] != '\n');

/*c-string terminated by Null character*/
str[n - 1] = '\0';

printf("The string you just entered is:%s\n", str);

i = 0;
while(str[i])
{
if(str[i] >= 'a' && str[i] <= 'z')
{
sum++;
}
i++;
}

printf("You entered %d small letters.\n", sum);

free(str);
}
现在就好使了!!

读书人网 >C语言

热点推荐