获取错误"Expression: string subscript out of range"
Getting error "Expression: string subscript out of range"
我不明白这里的问题。我已经研究过了,它编译得很好,但是当我运行程序时,它给了我"Debug Assertion Failed!"错误和上面的解释。
#include <iostream>
#include <string>
using namespace std;
bool checkVowel(char ch)
{
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return true;
default:
return false;
}}
int main()
{
string str;
char ch;
cout<<"Please enter a string, all vowels will be removed: ";
cin >> str;
for (int i=0;i=str.length();i++)
{
if (checkVowel(str[i]))
{
str=str.erase(i);
}}
cout << str;
}
这里有一个错误:
i=str.length()
应:i < str.length()
在初始代码中,当字符串非空时,i=str.length()
将始终返回true。因此,结果是您将超出字符串。
此外,当您找到一个元音时,您不希望增加索引,否则您将跳过下一个字符:
for (int i = 0; i < str.length(); )
{
if (checkVowel(str[i]))
{
str.erase(i,1);
}else{
i++;
}
}
最后一件事:str=str.erase(i);
是不必要的,只要str.erase(i,1);
就足够了。(您需要第二个参数为注释中指出的1)
如果条件错误,则应为for (int i=0;i <= str.length();i++)
也可以使用STL remove_if
remove_if(str.begin(), str.end(), checkVowel);
完整的程序将被。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool checkVowel(char ch){
switch(ch){
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return true;
default:
return false;
}
}
int main(){
string str;
char ch;
cout << "Please enter a string, all vowels will be removed: ";
cin >> str;
remove_if(str.begin(), str.end(), checkVowel);
cout << str;
}
相关文章:
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 解决方案在第 25 行执行错误'out of bounds'
- C++ 向量加减抛出"expression: vector subscript out of range."错误
- 从 MSVC14 切换到 MSVC16 会导致"compiler is out of heap space (C1060)"错误
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 如何解决'vector subscript out of range'错误?
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 空集"Out of bound iterator"
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 注册 Clang 检查器时出错:"out-of-line-definition of register"
- QList::operator[]中的断言失败<T>:QJoysticks 中的"index out of range"
- 尝试获取矩阵的正确对角线会导致"vector out of range"错误
- 运算符方法和返回对象"out-of-scope"?
- 如何使用 mpi 分散修复"vector subscript out of range"?
- 如何修复邻接列表中的"Debug Assertion Failed" "vector subscript out of range"
- "Vector subscript out of range",在返回声明?
- QList<T>::operator[]: "index out of range" 中的断言失败
- 多次调用存储过程时C++连接器"Commands out of sync" mySQL
- 如何处理C++'index out of bounds error'?
- MySQL 异常"connection lost during query"、"MySQL server has gone away"和"command out of sync"