希望程序可以把:
<YB><CB><ZZ><XX><><VV><><NN><MM><AA><SS><DD><FF><GG><HH><JJYYY><KK><></DX><QQ><WWW><EE><TT><YY>
这样的字符串
处理成:
<YB>
<CB>
<ZZ>
<XX>
<><VV><><NN>
<MM>
<AA>
<SS>
<DD>
<FF>
<GG>
<HH>
<JJYYY><KK><></DX>
<QQ><WWW><EE>
<TT>
<YY>
这样、、、
有问题的代码:
<YB><CB><ZZ><XX><><VV><><NN><MM><AA><SS><DD><FF><GG><HH><JJYYY><KK><></DX><QQ><WWW><EE><TT><YY>
这样的字符串
处理成:
<YB>
<CB>
<ZZ>
<XX>
<><VV><><NN>
<MM>
<AA>
<SS>
<DD>
<FF>
<GG>
<HH>
<JJYYY><KK><></DX>
<QQ><WWW><EE>
<TT>
<YY>
这样、、、
有问题的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
fstream InFile;
string bufferstr,strA,strB;
int LineCount = 0;
int repeatCount = 0;
int PosA = 0;
int PosB = 0;
string targetStr = "><";
int main()
{
InFile.open("test.xml",ios::in);
while(getline(InFile,bufferstr))
{
while(bufferstr.find(targetStr,0) != -1)
{
PosA = bufferstr.find(targetStr,0);
if((bufferstr.substr(PosA + targetStr.length() + 2,1) == ">"))
{
bufferstr.insert(PosA + 1,"\n");
}
}
cout << "line is:" << LineCount +1 << "\n";
cout << "处理过的bufferstr:" << bufferstr << " \n\n";
LineCount++;
}
InFile.close();
return 0;
}
解决方案
5
第二层循环里面bufferstr内容是不变的,所以while条件永真。
if语句改为bufferstr = bufferstr.insert(PosA + 1,”\n”); 再试一下。
if语句改为bufferstr = bufferstr.insert(PosA + 1,”\n”); 再试一下。
10
第二层循环中你bufferstr应该一直没变,里面的if也没被执行到
10
利用PosA来记录已经扫描过的位置
if((bufferstr.substr(PosB + targetStr.length() + 2,1) == “>”))这个逻辑有点不太懂
只有当找到”><“的位置的后面的第四个字符是”>”你才插入回车符,但又和题主贴出来想要达到的结果不太一样啊?
if((bufferstr.substr(PosB + targetStr.length() + 2,1) == “>”))这个逻辑有点不太懂
只有当找到”><“的位置的后面的第四个字符是”>”你才插入回车符,但又和题主贴出来想要达到的结果不太一样啊?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
fstream InFile;
string bufferstr,strA,strB;
int LineCount = 0;
int repeatCount = 0;
int PosA = 0;
int PosB = 0;
string targetStr = "><";
int main()
{
InFile.open("test.xml",ios::in);
while(getline(InFile,bufferstr))
{
while(bufferstr.find(targetStr,PosA) != -1)
{
PosB = bufferstr.find(targetStr,PosA);
if((bufferstr.substr(PosB + targetStr.length() + 2,1) == ">"))
{
bufferstr.insert(PosB + 1,"\n");
PosA += 4;
}
else
PosA++;
}
cout << "line is:" << LineCount +1 << "\n";
cout << "处理过的bufferstr:" << bufferstr << " \n\n";
LineCount++;
}
InFile.close();
return 0;
}
25
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//…
if (条件2) continue;
//…
if (条件3) return;
//…
}
原因是前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//…
b=fgetc(f);//可能此时已经feof了!
//…
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//…
b=fgetc(f);
if (feof(f)) break;
//…
}
相似的例子还可以举很多。
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//…
if (条件2) continue;
//…
if (条件3) return;
//…
}
原因是前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//…
b=fgetc(f);//可能此时已经feof了!
//…
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//…
b=fgetc(f);
if (feof(f)) break;
//…
}
相似的例子还可以举很多。