c++ - member function erase() not working in a loop -


i'm programming little game; stringname.erase() seems not working in 'for-loop' , want understand why, have other alternatives, don't understand what's going on in following code.

more explications of situation (important!):

guess char. 'tmgword' , 'word' of type string, and: tmgword = word ;

what understand code:

in first time,the 'while'-loop verifies if there 'guess' in string 'tmpgword'. true , for-loop working fine, right character(guess) verifies if-condition erased.

in second time: 'while'-loop verifies again if there 'guess' in string 'tmpgword'. true, , hence go 'for-loop' again; , 'if'-block ( right char found ) here erase() don't work, , enter in infinite loop.

when program finds right index using 'for-loop', break, , start search beginning in case there more occurrences of guess.

the problem is: program finds 'guess' again erase() won't delete it!

can explain please. here code:

while (tmpgword.find(guess,0) != string::npos )         {             (i = 0; < word.size(); i++) // verify input;              {                  if (word[i] == guess)                 {                     encword[i] = word[i];//i don't think line important                     tmpgword.erase(tmpgword.begin() + i);                     break;                 }              }         } 

after first erase, character positions in tmpgword not same in word.

string::find() returns position of element when it's found, can use instead of looping through word.

size_t pos = 0; while ((pos = tmpgword.find(guess, pos)) != string::npos) {     tmpgword.erase(pos, 1); } 

i've used pos starting position each call find() starts erased, rather searching beginning each time through (there can't occurrences before that, because they've been erased).


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -