我遇到了這個抨擊的問題,我不能放下,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