#include <stdio.h> #include <ctype.h> #include <stdlib.h> #define BUF_LEN 20 #define BUF_INCR 10 int main(void) { size_t buf_len = BUF_LEN; char *buffer = (char*)malloc(buf_len); char *temp =NULL; char *pbuffer1 = buffer; char *pbuffer2 = NULL; printf("Enter:\n"); //经典代码1,运行期动态分配内存 while((*pbuffer1++=getchar())!=‘\n‘) { if((pbuffer1-buffer)==buf_len) { buf_len+=BUF_INCR; if(!(temp = realloc(buffer,buf_len))) { printf("bullshit!"); exit(1); } pbuffer1 = temp + (pbuffer1 - buffer); buffer = temp; temp = NULL; } } *pbuffer1 = ‘\0‘; pbuffer1 = pbuffer2 = buffer; //经典代码段2,设置两个指针,对字符串进行操作,第三个指针进行全输出。 while((*pbuffer1)!=‘\0‘) { if(ispunct(*pbuffer1)||isspace(*pbuffer1)) { *pbuffer1++; continue; } else *pbuffer2++ = *pbuffer1++; } *pbuffer2 = ‘\0‘; printf("With the spaces and punctuation removed, the string is now:\n%s\n", buffer); free(buffer); return 0; }
时间: 2024-12-27 09:49:32