Skip to content

Instantly share code, notes, and snippets.

@johnhmj
Created May 1, 2010 15:40
Show Gist options
  • Save johnhmj/386428 to your computer and use it in GitHub Desktop.
Save johnhmj/386428 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 4096
void process(char* &_pChar, char* _string);
int main(void)
{
char InputBuffer[BUFFERSIZE];
char* p = NULL;
while ( 1 )
{
strcpy(InputBuffer, "");
printf("Input a name: ");
scanf("%s", InputBuffer);
// 輸入 -1 即跳出程式
if ( strcmp(InputBuffer, "-1") == 0 )
{
break;
}
process(p, InputBuffer);
}
// 顯示字串
printf("%s\n", p);
// 釋放記憶體
if ( p != NULL )
{
free(p);
}
system("PAUSE");
return 0;
}
void process(char* &_pChar, char* _string)
{
size_t _length_string = strlen(_string);
size_t _length_pChar = 0;
char* _buffer = NULL;
// 第一次輸入
if ( _pChar == NULL )
{
_pChar = (char*)calloc((_length_string + 1), sizeof(char));
strcpy(_pChar, _string);
}
// 第二次以後的輸入
else
{
_length_pChar = strlen(_pChar);
_buffer = (char*)calloc((_length_pChar + 1), sizeof(char));
strcpy(_buffer, _pChar);
free(_pChar);
_pChar = (char*)calloc((_length_pChar + _length_string + 1), sizeof(char));
strcpy(_pChar, _buffer);
strcat(_pChar, _string);
free(_buffer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment