2013-04-29 332 views
0

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

回答

1

resizetemp使用

string temp; 

temp.resize(inStringP.size()); 

之前,當你不知道在開始實際大小,你可以appendpush_backoperator+=

temp.append(1, inStringP[i]); 

or 

temp.push_back(inStringP[i]); 

or 

temp += inStringP[i]; 
+1

我不知道爲什麼,這已經downvoted?如果你通過元素訪問它,或者編譯器不知道它有多大,那麼字符串temp需要被賦予一定的大小。當你說temp [i] = inStringP [i]時,temp [i]可能超出界限? – FreudianSlip 2013-04-29 07:37:34

+0

謝謝大家的最佳答案,但我得走了「temp.resize ....」,第一次工作,再次感謝和該死的快速反應! – 420kscott 2013-04-29 07:48:20

2

你的應用程序崩潰是因爲下面的語句不分配任何元素temp,訪問temp[0]未定義的行爲

string temp; 

如果你想使用temp removeChar功能裏面,更好的辦法是const引用傳遞給inStringP

string removeChar(const string& inStringP){ 
} 

通過這樣做,你不需要做副本inStringP時輸入removeChar函數。

更好的方法是按照erase-remove idiom

嘗試:

string removeChar(string inStringP) 
{ 
    return inStringP.erase(std::remove(sample.begin(), sample.end(), 'p'), sample.end()); 
} 
0

我會推薦;

string removeChar(string inStringP){ 
    string temp; 
    int len = inStringP.length(); 
    for(int i = 0;i < len;i++){ 
     if(inStringP[i] != 'p'){ 
     temp.push_back(inStringP[i]); 
     } 
    } 
    return temp; 
} 

因爲你的邏輯給出了無編譯時間的錯誤,但它是一個運行時錯誤。您的代碼實際上的工作原理如下:

string temp; 
    temp[0] = 'P'; 
    temp[1] = 'e'; 
    temp[2] = 't'; 
    temp[3] = 'e'; 
    temp[4] = 'r'; 
    temp[5] = ' '; 
    //s[6] = 'p'; 
    temp[7] = 'i'; 

這是超出範圍的錯誤。

0

當您使用std::string時,您也可以使用算術運算符。

你可以做這樣的事情,

for(int i=0;i<=inStringP.length();i++) 
    { 
     if(inStringP[i]!='p') 
     { 
     temp += inStringP[i]; 
     cout<<temp<<endl; 
     } 
    } 

我試過g++ 4.6.3你的代碼沒有給出任何錯誤。然而,它在for循環的末尾給 一個空的temp;

有了,編譯器還沒有一個尺寸temp

此外,如果使用相同的itempinStringP 假設,我們在性格e將跳過if block和+1 itemp中相應的 位置將保持不變。

此外,string.length()返回字符串的長度不包括\0