我遇到了这个抨击的问题,我不能放下,Visual C++ 2010不断告诉我:“表达式:字符串下标超出范围”的问题。我认为我运行的循环比“inStringP.length()”的长度长,因此我添加了&从for循环的条件测试中的整数中减去1或2,但这不会导致成功。谷歌是不是感觉其一贯的天才自今天要么.....字符串下标超出范围(C++)
#include <iostream>
#include <cstdlib>
#include <string>
#include "stdAfx.h"
using namespace std;
string removeChar(string inStringP){
string temp;
for(int i=0;i<inStringP.length()-1;i++){
if(inStringP[i]!='p'){
temp[i]=inStringP[i];
}
}
return temp;
}
int main(){
string sample = "Peter picks a peck of pickled peppers";
cout<<removeChar(sample)<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
我不知道为什么,这已经downvoted?如果你通过元素访问它,或者编译器不知道它有多大,那么字符串temp需要被赋予一定的大小。当你说temp [i] = inStringP [i]时,temp [i]可能超出界限? – FreudianSlip 2013-04-29 07:37:34
谢谢大家的最佳答案,但我得走了“temp.resize ....”,第一次工作,再次感谢和该死的快速反应! – 420kscott 2013-04-29 07:48:20