cout << "If you would like to find/replace or copy/paste, enter find or copy: " << endl;
cin >> answer;
cin.ignore();
if(answer == "find"){
cout << "Enter substring to find: " << endl;
cin >> userInput2;
cin.ignore();
cout << "Do you want to find if/where the substring occurs, delete it, or replace it (find, delete, replace)? " << endl;
cin >> answer;
cin.ignore();
position = userInput.find(userInput2);
if(answer == "find"){
if(userInput.at(position) == string::npos){
cout << userInput2 << " was not found.";
}else{
cout << userInput2 << " was found at position "<< position << "." << endl;
}
我认为错误可能就在这里:
position = userInput.find(userInput2);
if(answer == "find"){
if(userInput.at(position) == string::npos){
cout << userInput2 << " was not found.";
}else{
cout << userInput2 << " was found at position "<< position << "." << endl;
}
找到答案,找到并输入userInput 2是起司,应该返回userInput was not found
或cheese was not found
,但我得到的是:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 18446744073709551615) >= this->size() (which is 14)
帮助我知道我做错了。
答案 0 :(得分:1)
userInput.at(position) == string::npos
不会执行您想要的操作,因为如果position
已经是string::npos
,则您是在要求string::at
从无效位置获取字符。如果您阅读了已提供给我们的错误消息,则可以看到它说明了这一事实:您正在将一个超出范围的疯狂值传递给at
,该值显然比您的长度大字符串。
您还应该阅读string::find
(有些here)的文档,其中明确指出如果找不到这样的子字符串,该函数将返回npos。 >
尝试做
if(position == string::npos){
相反。