字符读取的问题
ifstream In( "D:\\StrTest\\baidu.txt ");
ofstream Out( "D:\\StrTest\\Mid.txt ");
vSpaceBuf = " ";
while(!In.eof())
{
vChar = In.get();
if(vChar == ' < ')
vStreamBuf < < '\n ';
if(vChar < 0x20)
continue;
if(vChar == ' < ')
vStreamBuf < < '\n ';
vStreamBuf < < vChar;
if(vChar == '> ')
vStreamBuf < < '\n ';
}
我的程序是逐个读取字符,遇到一对 " <...> " 在其后加 "\n " ,但是我想 在遇到 (..)中的 " <...> "时不在 <..> 后加 "\n ",例如:( ' <a href= "http://passport.baidu.com/?login&tpl=mn&u= '+escape(location.href)+ ' "> 登录 </a> ') 直接把这一条读进去,而不对 " <> "处理,
我该怎么做 ??
[解决办法]
上面有点错误,应该这样:
bool bIn = false;
while (!In.eof())
{
vChar = In.get();
if (vChar == '( ')
{
bIn = true;
continue;
}
if (vChar == ') ')
{
bIn = false;
continue;
}
if (!bIn && (vChar == ' < ' || vChar == '> ')
{
vStreamBuf < < '\n ';
continue;
}
vStreamBuf < < vChar;
}
[解决办法]
最好的办法,站在巨人的肩膀上,用正则表达式:
参考网站:
http://www.regexlab.com/zh/deelx/
下载deelx.zip;
下面是个示例:
查找注释
在一段 C++ 源代码文本中,查找注释。
#include "deelx.h "
int find_remark(const char * string, int & start, int & end)
{
// declare
static CRegexpT <char> regexp( "/\\*((?!\\*/).)*(\\*/)?|//([^\\x0A-\\x0D\\\\]|\\\\.)* ");
// find and match
MatchResult result = regexp.Match(string);
// result
if( result.IsMatched() )
{
start = result.GetStart();
end = result.GetEnd ();
return 1;
}
else
{
return 0;
}
}
int main(int argc, char * argv[])
{
char * code1 = "int a; /* a */ ";
char * code2 = "int a;//体 ";
int start, end;
if( find_remark(code1, start, end) )
printf( "In code1, found: %.*s\n ", end - start, code1 + start);
else
printf( "In code1, not found.\n ");
if( find_remark(code2, start, end) )
printf( "In code2, found: %.*s\n ", end - start, code2 + start);
else
printf( "In code2, not found.\n ");
return 0;
}
[解决办法]
哈哈,要是我,我就这么做啦
CStdioFile stdFile;
stdFile.open(.....);
// 一次性读出全部文本
CString strText;
CString strLine;
while(1)
{
if( strFile.ReadString(strLine) == 0 )
break;
strText += strLine;
strLine.Empty();
}
//使用 find 查找,做个递归函数
FormatString(strText,0);
void FormatString(strText,int nStart)
{
int nFindLeft = strText.Find(nStart, " < ");
if( nFindLeft == -1 ) // 没有找到 <
return;
int nFindRight = strText.Find(nFindLeft, "> ");
if( nFindRight == -1 ) // 没有找到 >
return;
// 查看是否在修改条件内 再找两边是否有 ()
.....
// 可以修改
strText.Insert(nFindRight, "\r\n ");
// 重新再找
FormatString(strText,nFindRight);
}