接收一个未知长度的字符串(人为输入,长度不定)

int main(int argc, char** argv)
{
int strLen = 5;
char ch;
char* str = (char*)malloc(sizeof(char*) * strLen);
int count = 0;
printf("Please input a string: ");
do 
{
ch = getchar();
count++;
if (count >= strLen)
{
str = (char*)realloc(str, sizeof(char*) * (++strLen));
}
str[count-1] = ch;
} while (ch != '\n');
str[count] = '\0';
puts(str);
return 0;
}
posted @ 2015-04-19 22:06  hust_liye  阅读(802)  评论(0)    收藏  举报