C语言录入无限制长度字符串?題目是錄入無限制個字符放在一個字符串內, 并統計輸入了多少個小寫字母.可是我
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);
}
现在就好使了!!