ccf 2015年9月第三题,是一个简单的字符串替换的程序,但是我的程序好像都没有正常读入输入,求大佬帮忙看一下
#include<iostream>
#include<string>
using namespace std;
void string_replace( std::string &strBig, const std::string &strsrc, const std::string &strdst)
{
std::string::size_type pos = 0;
std::string::size_type srclen = strsrc.size();
std::string::size_type dstlen = strdst.size();
while( (pos=strBig.find(strsrc, pos)) != std::string::npos )
{
strBig.replace( pos, srclen, strdst );
pos += dstlen;
}
}
int main()
{
int line_num=0,replace_num=0;
cin>>line_num>>replace_num;
string *input=new string[line_num];
for(int n=0;n<line_num;n++)
{
getline(cin,input[n]);
}
string *re_from=new string[replace_num];
string *re_to=new string[replace_num];
for(int n=0;n<replace_num;n++)
{
//cout<<'+'<<'\n';
cin>>re_from[n]>>re_to[n];
}
for(int n=0;n<line_num;n++)
{
string tem1="{{ "+re_from[n]+" }}";
string tem2=re_to[n].substr(1,re_to[n].length()-1);
string_replace(input[n],tem1,tem2);
}
for(int n=0;n<line_num;n++)
cout<<input[n]<<'\n';
return 0;
}
https://blog.csdn.net/code_mlym/article/details/53694192
for(int n=0;n<replace_num;n++)
cin>>re_from[n]>>re_to[n];
for(int n=0;n<line_num;n++)
string tem1="{{ "+re_from[n]+" }}";
string tem2=re_to[n].substr(1,re_to[n].length()-1);
string_replace(input[n],tem1,tem2);
}
在这两个循环里,输入时re_from和re_to的大小都是(replace_num)m,而在替换的时候用的是(line_num)n,这里显然有越界的问题。
其次第二个循环代表第n行用第n个re来替换,这个肯定是不对的,题中示例就是第3行用的是第0个替换,应该是每行都查询所有替换。
而且你这样查询有个问题,比如模板里有"{{ name {{ name }} }}"这种情况的话应该是不做处理,但是你的程序会把第二个name替换掉,这个是需要考虑的。