On Feb 28, 2:00 am, yogi_bear_79 <yogi_bear...@yahoo.comwrote:
On Feb 26, 10:58 pm, Micah Cowan <mi...@cowan.namewrote:
yogi_bear_79 wrote:
[...]
James, I think your code was a bit further ahead than I am
supposed to know at this point!
I'm not sure how? You should be learning the standard
algorithms long before the specific functions of std::string
(which I probably wouldn't bother teaching at all), and you
should be learning iterators before dealing with pos in a
string. (But of course, you can apply the exact same algorithm
using the position and std::string::find instead of the
iterators and std::search.)
#include <iostream>
#include <string>
using namespace std;
int findIt(const string &str1, const string &str2);
int main ()
{
string quote;
string findMe;
cout << " \n Enter a sentence or two:" << endl;
getline (cin,quote);
cout << " \n Enter string to search for:" << endl;
getline (cin,findMe);
cout << findIt(quote, findMe);}
int findIt(const string &str1, const string &str2)
{
size_t pos = 0;
int x = 0;
while (pos != string::npos) {
pos = str1.find(str2, pos);
cout << pos<<endl;
pos = pos+str2.size();
What happens in this line when str1.find returns
std::string::npos?
}
You really do want the loop I proposed:
for ( size_t pos = str1.find( str2 ) ;
pos != std::string::npos ;
pos = str1.find( str2, pos + str2.size() ) {
// Whatever you do when you find a match...
}
As a general rule: prefer for, with no modification of the
control variable outside of the third part. It's much easier to
get right. (If you need the value of the control variable after
the loop, either move the first part of the for before the loop,
or rewrite the loop as a while. And of course, don't try to
force things which don't fit into this pattern.)
You're problem, of course, is that you're modifying the control
variable twice in the loop, and the first modification might
cause the loop invariant (pos != std::string::npos) to be
invalid. The only operations which should possibly invalidate
the loop invariant should be at the end of the loop. A for
makes this clearer---the only operations which might invalidate
the loop invariant should be in the third part of the for.
return x;
}
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34