简体   繁体   中英

Error with string library in c++ :: libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string (lldb)

I am asked to ask for a phrase and a word and replace all the words for " * ".

Example: Phrase: I love dogs but my sister doesn't like dogs

Word: dogs

Final Phrase: I love * but my sister doesn't like *

When i put a cout of the phrase inside the loop it displays it as it should be but i am getting an "libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string (lldb)" error

You need at least 10 reputation to post images: https://imgur.com/5Zf9ys5.jpg

#include <iostream>
#include <string>
using namespace std;
int main()
{
string frase;
string palabra;
getline(cin,frase);
getline(cin,palabra);
int longitud = palabra.length();
int encontrar = frase.find(palabra);

while(encontrar != 1){
    if(encontrar != 1){
        encontrar = frase.find(palabra);
        frase.erase(encontrar,longitud);
        frase.insert(encontrar, " * ");

    }
    cout<<frase<<endl;
}

}

You are using string::find in the wrong manner.

string::find returns:
- The position of the first character of the first match.
- string::npos if no matches were found.

So your check should have a comparison with string::npos . You can modify your while loop like this:

while(encontrar != string::npos){
        frase.erase(encontrar, longitud);
        frase.insert(encontrar, " * ");
        encontrar = frase.find(palabra);
}

See demo here .

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