2016-05-30 45 views
-2

我想刪除字符串中的空格,但是當我運行我的程序並進入「hello world」時,它沒有跟我說話。它崩潰,這表明:爲什麼我無法刪除字符串的空間?

enter image description here

#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
    string str; 
    getline(cin,str); 
    int space; 
    while(str.find(' ')>=0) {//something wrong happened in the loop 
     space = str.find(' '); 
     str.erase(space,1); 
    } 
    cout<<str<<endl; 
    return 0; 
} 

我很困惑極了,因爲我不知道爲什麼我的字符串是出於range.So如何解決?提前致謝。

+0

我想知道爲什麼我的程序崩潰而不是如何刪除空間 – fgksgf

+1

'#include ':這是一個不 - no ... – 3442

+0

我看,比ks爲您提醒。 – fgksgf

回答

4

編輯:

所以,真正的問題是,爲什麼它拋出一個錯誤。 當訪問不在容器範圍內的索引時,會引發std :: out_of_range異常。

正如在評論中提到的問題在於while(str.find(' ')>=0)。當它找不到任何東西時,string::find返回string::nposstring::npos定義爲-1,但由於它是size_t類型,所以它不能小於0.因此,該值是最大可能的無符號整數,因爲它的類型是「循環」的。

所以它會是4294967295,或者是系統上size_t類型的最大值以及編譯標誌的最大值。

回到問題while(str.find(' ')>=0),作爲所述的str.find回報率將始終是正值,所以你永遠不會停止循環,最後得到一個std::out_of_range異常,因爲您嘗試訪問str[string::npos]這是不可能的。

的「更好」,而隨後將是:while(str.find(' ') != string::npos)

初步答案:。

還有另一種方式來做到這一點使用std::remove算法它提供了一系列爲std ::擦除

#include <iostream>  
#include <string> 
#include <algorithm> 

int main() 
{ 
    std::string str = "this is a line"; 

    std::cout << "before: " << str << std::endl; 

    str.erase(std::remove(str.begin(), str.end(), ' '), str.end()); 

    std::cout << "after: " << str << std::endl; 
} 
+0

謝謝,但我仍然想知道爲什麼我的程序崩潰而不是如何刪除空間。 – fgksgf

+0

str.find總是返回值> = 0 當它沒有找到一個字符時,它返回'string :: npos',所以你的代碼應該是'while(str.find('')!= string :: npos )' – vianney

+0

那麼,這是非常友善的:)。但string :: npos的值是-1。這就是爲什麼我很困惑。 – fgksgf