Some history, hopefuly I am getting this right :)
A long time ago someone decided that the word 'word' meant the 'size of the default instruction or data chunk that a cpu can consume', roughly. So way back when I was getting into it, computers were 16 bit and a word was 2 bytes. Then 32 bit machines came out, and words were 4 bytes. Now we have 64 bit but because of backward compatible confusion a word might be 32 or 64 depending on the compiler, OS, and settings. Soon we should have 128 bits; many PC already have registers this big but not a bus or instruction this size (yet).
All that to say 'size_t' probably "should be" the size of the word of the CPU, but it may not be for various reasons. Its easy to check it, but its easier to use auto. Given the backwards compatible focus, if we get 128 bit machines tomorrow it would not surprise me if they supported 4 byte words just as 64 bit machines do now.
Neither long nor size_t are well defined. Both can change by compiler settings/OS/etc. I like to use the explicit ones or auto (there are explicitly named integers that tell how many bytes they have, or bits, like __int64 in visual studio, or the C99 ones). Ill also use int, when I don't care at all.
I am not sure how to fix what you have without a bit of rewrite. Anyway, try this version/ approach?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
int main ()
{
string needle = "needle";
string haystack = "blahneedlexneedlexxneedleneedlen ";
int needle_appearances = 0;
int i = 0;
//cout<< "Enter the haystack: \n";
//getline(cin, haystack, '\n');
//cout<< "Enter the needle: \n";
//cin>>needle;
while(i!= string ::npos)
{
i = haystack.find (needle, i);
if(i!= string ::npos)
needle_appearances++;
i++;
}
cout << "The word " << needle << " has appeared " << needle_appearances << " times in your haystack.";
}
|