【我要循环处理输入的字符串,每次长度不定,但处理完毕后要连接在一起,如何将结果存放在一个指针字符呢】
我要循环特殊处理输入的字符串,每次长度不定,但处理完毕后要连接在一起,如何将结果存放在一个指针字符呢?
该如何对指针字符进行操作或者使用函数呢
[解决办法]
是不是想这样的??
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *desStr;
int i;
char *str[10];
for (i=0; i <10; i++)
str[i] = (char *)malloc(20);
desStr = (char *)malloc(100);
strcpy(desStr, "\0 ");
for (i=0; i <10; i++)
{
scanf( "%s ", str[i]);
strcat(desStr, str[i]);
}
printf( "%s\n ", desStr);
for (i=0; i <10; i++)
free(str[i]);
free(desStr);
return 0;
}
[解决办法]
#include <iostream>
using namespace std;
void main()
{
int istep=1;
int max_size = 1024;
char * pfinal=new char[istep * max_size];
memset(pfinal,0,istep * max_size);
char * str=new char[istep * max_size];
int cnt=0;
while(cin.getline(str,max_size, '\n '))
{
if(!strcmp(str, "exit "))
break;
cnt += cin.gcount();
if( cnt > istep*max_size -1 )
{
istep++ ;
char * tmp = pfinal;
pfinal=new char[istep * max_size];
strcpy(pfinal,tmp);
delete [] tmp;
tmp=0;
}
strcpy(pfinal+strlen(pfinal),str);
}
cout < <pfinal < <endl;
if(str)
{
delete [] str;
str=0;
}
if(pfinal)
{
delete[] pfinal;
pfinal=0;
}
system( "pause ");
}