C++ 获取错误“;表达式:字符串下标超出范围;
我不明白这里的问题。我已经研究过了,它编译得很好,但是当我运行程序时,它给出了“Debug Assertion Failed!”错误和上面的解释C++ 获取错误“;表达式:字符串下标超出范围;,c++,visual-studio-2010,C++,Visual Studio 2010,我不明白这里的问题。我已经研究过了,它编译得很好,但是当我运行程序时,它给出了“Debug Assertion Failed!”错误和上面的解释 #include <iostream> #include <string> using namespace std; bool checkVowel(char ch) { switch(ch) { case 'a': case 'A': case 'e': case 'E':
#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;
}
#包括
#包括
使用名称空间std;
布尔校验元音(char-ch)
{
开关(ch)
{
案例“a”:
案例“A”:
案例“e”:
案例“E”:
案例“i”:
案例“I”:
案例“o”:
案例“O”:
案例“u”:
案例“U”:
返回true;
违约:
返回false;
}}
int main()
{
字符串str;
char ch;
cout-str;
对于(int i=0;i=str.length();i++)
{
if(检查元音(str[i]))
{
str=str.erase(i);
}}
cout这里有一个错误:
i=str.length()
应该是:
i < str.length()
最后一件事:str=str.erase(i);
不是必需的,只要str.erase(i,1);
就足够了。(您需要第二个参数,如注释中指出的1)。这里有一个错误:
i=str.length()
应该是:
i < str.length()
最后一件事:str=str.erase(i);
不是必需的,只要str.erase(i,1);
就足够了。(您需要注释中指出的第二个参数为1)。对于条件错误,它应该是for(int i=0;i str;
删除_if(str.begin()、str.end()、check元音);
cout如果条件错误,则应为(int i=0;i str;
删除_if(str.begin()、str.end()、check元音);
如果在遍历对象时对其进行修改,请务必非常小心。请注意,循环每次删除一个字符时都会跳过一个字符——它会移动到下一个位置,跳过由于“擦除”操作而“滑入”当前的字符。(这对于if
循环来说不是一个很好的选择。如果调用erase
,请使用while
,不要增加i
)如果在遍历对象时对其进行修改,请务必小心。请注意,循环每次删除一个字符时都会跳过一个字符——它会移动到下一个位置,跳过由于“擦除”操作而“滑入”当前位置的字符。(这对于if
循环来说是一个很差的选择。在调用erase
时使用while
并且不要增加i
)如果你给字符串::erase
一个数字参数,它将擦除到字符串的末尾。他应该使用str.erase(i,1)是的,你是正确的,修正了我的答案…谢谢你指出这一点。如果你给string::erase
一个数字参数,它将擦除到字符串的末尾。他应该使用str.erase(i,1);
是的,你是正确的,修正了我的答案…谢谢你指出这一点。
#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;
}