0

I have encountered something very strange. The code I am having trouble with is:

int stringPos;
int found1;
while (stringPos < 1);
{
    //start searching inString for framen starting at foundn and record
    found1 = inString.find(frame1, found1);
    cout << found1 << endl;


    //if return is a number, push back foundn to a vector
    if (found1 != -1)
    {
        foundPositions.push_back(found1);
    }
    //if return is npos, then break the loop
    else
    {
        stringPos=1;
    }

    //add 1 to foundn so that the search would continue from where the
    //search ended last
    found1+=1;
}

The strange thing is that when I put cout << found1 << endl; below the line found1 = inString.find(frame1, found1); the loop executes properly. However, if I don't have the cout << found1 << endl; it enters an infinite loop...

Any suggestions? THANKS!

ktosayev
  • 17
  • 5

3 Answers3

6

This is a mistake (and uses an unitialized variable):

while (stringPos < 1);

as it is equivalent to:

while (stringPos < 1) {}

If this did not enter an infinite loop the code following it would be executed once only. To correct:

  • Initialize the variables stringPos and found1.
  • Use type size_t for stringPos and found as std::string::find() does not return an int, but returns size_type (usually size_t).
  • Use std::string::npos instead of -1 to test for not found.
  • Remove the trailing semi-colon.
hmjd
  • 120,187
  • 20
  • 207
  • 252
2

Your program has undefined behavior, because you are trying to use the value of an uninitialized variable here:

while (stringPos < 1)
//     ^^^^^^^^^
//     This is uninitialized

And here:

found1 = inString.find(frame1, found1);
//                             ^^^^^^
//                             This is uninitialized

Besides, even supposing your variables were initialized, you have a semicolon that makes your while loop either a no-op or an infinite loop (as hmjd correctly points out in his answer).

Community
  • 1
  • 1
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
0

I would start off by initializing the stringPos and found1 variables.

John Sheridan
  • 446
  • 4
  • 8