2011-07-16 23 views
2

我正在製作控制檯計算器,並且希望刪除用戶在使用該程序時可能輸入的任何空格。這是代碼:該代碼應該返回沒有空格的字符串,但它返回字符串,直到第一個空格字符

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

using namespace std; 

int main() 
{ 
    string str; 
    std::cout<<"Enter sum): "; 
    cin>>str; 
    str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end()); 
    cout<<str; 
    system("pause"); 
    return 0; 
} 

如果我進入2 + 2 =,輸出應該是2 + 2 = 但輸出:2 我使用了錯誤的功能我在這裏?

+0

也許這可以幫到您? http://stackoverflow.com/questions/83439/remove-spaces-from-stdstring-in-: [1] [1] [在C++中取下的std :: string空間] c – Patrik

回答

1

您使用remove_iferase是好的。你的輸入方法不是。 operator>>是空格分隔的。改爲使用getline

int main() 
{ 
    string str; 
    std::cout<<"Enter sum): "; 
    getline(cin,str); 
    str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end()); 
    cout<<str;  
    return 0; 
} 
+0

謝謝。這個簡單的解決方案效果很好。 –

4

問題是獲取用戶輸入,而不是剝離空間。

刪除空格的代碼是正確的,因爲您可以see for yourself on IDEone

問題是,運算符std::istream::operator >>在遇到第一個空格字符時停止讀取輸入。您應該使用另一個功能(例如getLine)。

+0

+1我不知道IDEone - 謝謝。 – slashmais

0

我用下面的功能我寫道:

std::string& ReplaceAll(std::string& sS, const std::string& sWhat, const std::string& sReplacement) 
{ 
    size_t pos = 0, fpos; 
    while ((fpos = sS.find(sWhat, pos)) != std::string::npos) 
    { 
     sS.replace(fpos, sWhat.size(), sReplacement); 
     pos = fpos + sReplacement.size(); 
    } 
    return sS; 
} 

你可以使其適應您的需求。

+0

你的函數和['boost :: algorithm :: replace_all'](http://www.boost.org/doc/libs/1_47_0/doc/html/boost/algorithm/replace_all.html)一樣,但是在一個非常有效的方式。 –