【发布时间】:2022-11-16 23:24:52
【问题描述】:
我在任何地方都找不到它,所以我来了
#include <iostream>
using namespace std;
int main()
{
string napis;
string new_napis = "";
cout << "Give string: " << endl;
cin >> napis;
int length = napis.length();
string search = "pies";
size_t position = napis.find(search);
if (position != string::npos){
cout << "Found on position: " << position << endl;
} else {
cout << "Not found" << endl;
}
for (int i = 0; i <= length; i++){
if (napis[i] > 96 && napis[i] < 123){
new_napis.insert(i, 1, napis[i]);
} else {
cout << "";
}
}
cout << "string without numbers: " << new_napis;
return 0;
}
那是错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::insert: __pos (which is 1) > this->size() (which is 0)
基本上我在这里尝试做的是从输入中获取一个字符串并将其转换为新字符串但没有数字和其他东西,只有纯字母,我在互联网上的某个地方发现 i <= lenght 可能是一个问题但是当我将其更改为 i = lenght 它什么也没做,只需复制粘贴旧字符串
【问题讨论】:
-
string new_napis = "";创建一个空字符串,就像string new_napis;一样。您可以使用+=或push_back()将符合条件的字符添加到末尾。i <= length也会越界访问字符串,应该是<。 -
i <= lenght绝对是个问题,因为它会导致napis[i]被越界访问。 -
请注意,当
napis[i]不在 96 和 123 之间时,i仍会增加,但new_napis不会。下次调用insert时会出现错误。 -
不要让你的代码的读者(包括你未来的自己)猜测你的代码应该做什么。
if (napis[i] > 96 && napis[i] < 123)应该更改为使用名称描述该条件含义的函数。我猜该代码是 ascii-ist,并且该测试应该检测小写字母。这已经在标准库中为您完成了:if (std::islower(napis[I]))更清晰,即使字符编码不是 ASCII 也会给出正确的结果(当然,这很不寻常,但如果您不构建不可移植性不需要)。 -
另外,如果你想复制全部letters 你需要复制所有字母,而不仅仅是小写字母。所以
if (std::isalpha(lapis[I]))是合适的。
标签: c++