简体   繁体   中英

while (_index != string::npos) doesn't seem to be stopping the loop

My code counts spaces in string temp , which works fine. Later in the code I have a similar loop that does not end as expected.

Based on my debugging and some research, I've determined that the while loop isn't stopping when it is supposed to the second time around, so an exception is thrown ( std::out_of_range )… Why? Both while loops' conditions are identical, so they should behave the same, right? That is, they should both stop looping when find() didn't find a space…

First part of the code:

// Just find out how many spaces are in the temp string for now
// Find index (position in the string) of the first space in temp string
_index = temp.find( " " );

// Loop as long as there are still spaces in temp string
while (_index != string::npos) {
    // Find the index of the next space
    _index = temp.find(" ", _index + 1);

    // Keep track of how many spaces are in temp string
    count++;
}

Later (don't mind my debugging code interspersed in there):

// If the amount of spaces is just right, i.e. there are exactly SIZE - 1 spaces
if (count == SIZE - 1) {
    cout << "\n\n  - Inside the if (count == SIZE - 1) block\n"
         << "  - temp = \"" << temp << "\", temp's size = " << temp.length()
         << "\n\n";

    // This time, we're removing the spaces from the temp string in order to
    // be able to search it for any non-number characters
    // Find index of the first space in the temp string
    _index = temp.find(" ");

    cout << "  - The first temp.find(\" \") yields: " << _index << "\n\n";

    // Loop as long as there are still spaces in temp string
    while (_index != string::npos) {
        cout << "  - Right before temp.replace() in the loop\n"
             << "  - _index = " << _index << "\n\n";

        // Remove the space in temp string
        temp.replace(_index, 1, "");

        // find the index of the next space
        _index = input.find(" ", _index + 1);
    }
    // …
}

Within the second loop you reference a variable input instead of temp .

_index = input.find( " ", _index + 1 );`

Therefore the loop does never terminate. This you don't do within the first while-loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM