C++primer的一道习题6.15
题目是:
写一个程序,已知下列字符串
"/.+(STL).*$1"
用erase(pos,count)去掉除了"STL"外的所有字符。
我写程序如下:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
string t = "/.+(STL).*$1/";
string filt_elem = "./+)(*$1";
string::size_type pos = 0, begin_pos = 0;
cout << t <<endl;
while (pos = t.find_first_of(filt_elem,begin_pos)
!= string::npos)
{
cout << "After erase" << t[pos] << "is:" << endl;
t.erase(pos,1);
cout << t << endl;
//因为每次删除一个字符后,应该从前一个字符开始查找
begin_pos+=pos-1;
}
cout << "After while loop:" << t << endl;
return 0;
}
但是结果很奇怪:
下面是结果:
是一个死循环,而且除了第一个/外所有的字符都被删除了。
为什么?
Ps:请不要叫我去找题解,我有,但是我使用了另一种方法来解决这个问题。
谢谢大家!