just my practice. //read a sentence with "()" in it and replace everything in () with "(deleted)".
1)read the sentence to a vector.
2) stack the vector into a stack >.
3) find the positions of both "("
and ")"
4) remove the elements and replace with "(deleted)" in
vector
5) output the vector.
ie. input "this is (a) duck", output should be "this is (deleted) duck". thanks in advance.
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main ()
{
cout<<"please enter a series of words with parenthes"<<endl;
vector<string> svec;
string word;
while (cin>>word)
svec.push_back(word);
stack<string, vector<string> > strStack(svec);
vector<string>::iterator pos1 ,pos2;
for (vector<string>::iterator counter=svec.end(); strStack.empty()==false; --counter)
{
if(strStack.top()==")") pos1=counter-1;
if(strStack.top()=="(") { pos2=counter-1; break; }
strStack.pop();
}
svec.insert(svec.erase(pos2,pos1),"(deleted)");
for(vector<string>::iterator iter=svec.begin(); iter!=svec.end(); )
cout<<*iter++<<" "<<flush;
return 0;
}
sorry. output is: I think the problem is stack > strStack(svec); cause I couldn't cout stack; the codes above this should be fine (i cout'ed them);
please enter a series of words with parenthes
this is (a) duck
Segmentation fault
counterto move fromsvec.end()to...well, beyond the beginning ofsvec. Userbegin()and stop iterating when you hitrend().