当文本文件如下写的时候hello /n world /n希望控制台打印为:helloworld
#include <iostream.h>#include <stdio.h>#include <afx.h>
void main(){ FILE *fp; fp = fopen("string.txt","a+"); if(fp == NULL) { cout << "error!" << endl; return; }
int i =0; char buff[1024]; CString strTemp;
char *pBuffBegin, *pBuffEnd; while(fgets(buff, 1024, fp)!=NULL) { i = strlen(buff); cout<< buff; buff[i] ='//'; buff[i+1] = 'n'; buff[i+2] ='/0'; pBuffEnd = pBuffBegin = buff;
while (*pBuffEnd != '/0') { strTemp.Empty(); if(*pBuffEnd == '//' && *(pBuffEnd + 1) == 'n') { if(pBuffBegin == pBuffEnd) { cout << "空格" <<endl; } else { while(pBuffBegin < pBuffEnd) { strTemp += *(pBuffBegin++); } cout << strTemp << endl; } pBuffEnd +=2; pBuffBegin = pBuffEnd; } else { pBuffEnd++; } } cout << endl << endl; } fclose(fp); }
改良版
// AA.cpp: implementation of the AA class.//#include <iostream.h>#include <stdio.h>#include <afx.h>
void main(){ FILE *fp; fp = fopen("string.txt","a+"); if(fp == NULL) { cout << "error!" << endl; return; }
int ePos =0; char buff[1024]; CString strTemp;
char *pBuffEnd; while(fgets(buff, 1024, fp)!=NULL) { ePos = strlen(buff); cout<< buff; buff[ePos] ='//'; buff[ePos+1] = 'n'; buff[ePos+2] ='/0'; pBuffEnd = buff;
while (*pBuffEnd != '/0') { if(*pBuffEnd == '//' && *(pBuffEnd+1) =='n') { if(strTemp.GetLength() != 0) cout << strTemp << endl; strTemp.Empty(); pBuffEnd++; } else { strTemp += *pBuffEnd; } pBuffEnd++; } cout << endl << endl; } fclose(fp); }
改良版
// AA.cpp: implementation of the AA class.//#include <iostream.h>#include <stdio.h>#include <afx.h>
void main(){ FILE *fp; fp = fopen("string.txt","a+"); if(fp == NULL) { cout << "error!" << endl; return; }
int ePos =0; char buff[1024]; CString strTemp;
char *pBuffEnd; while(fgets(buff, 1024, fp)!=NULL) { ePos = strlen(buff); cout<< buff; buff[ePos] ='//'; buff[ePos+1] = 'n'; buff[ePos+2] ='/0'; pBuffEnd = buff;
while (*pBuffEnd != '/0') { if(*pBuffEnd == '//' && *(pBuffEnd+1) =='n') { if(strTemp.GetLength() != 0) cout << strTemp << endl; strTemp.Empty(); pBuffEnd++; } else { strTemp += *pBuffEnd; } pBuffEnd++; } cout << endl << endl; } fclose(fp); }