2016-08-14 29 views
-1

我已經看過這兩個問題:在C++字符串刪除空格不起作用

  1. Remove spaces from std::string in C++
  2. remove whitespace in std::string

出於某種原因,我永遠無法得到的解決方案正常工作。在我的程序中,我收集來自用戶的輸入並將其傳遞給std::string。從那裏,我想刪除它的所有空間。例如,如果用戶輸入「3 + 2」,我希望它變成「3 + 2」。

會發生什麼,無論在第一個字符串保存之前。這是我的程序:

#include <iostream> 

std::string GetUserInput() { 
    std::cout << "Please enter what you would like to calculate: "; 
    std::string UserInput; 
    std::cin >> UserInput; 
    return UserInput; 
} 
int PerformCalculation(std::string Input) { 
    Input.erase(std::remove_if(Input.begin(), Input.end(), ::isspace), Input.end()); 
    std::cout << Input; 
    return 0; 
} 
int main() { 
    std::string CalculationToBePerformed = GetUserInput(); 
    int Solution = PerformCalculation(CalculationToBePerformed); 
    return 0; 
} 

所以當我運行這個程序並輸入「3 + 2」,輸出是「3」。

這裏是我的控制檯:

Please enter what you would like to calculate: 3 + 2 
3 
Process finished with exit code 0 

我無法弄清楚如何解決這個問題。我甚至嘗試過使用包含使用正則表達式來移除所有\s字符的解決方案,這給了我同樣的問題。

+4

使用調試器逐步完成,你應該看到你真正的問題。 – chris

+0

@ DOUGLASO.MOEN,我不太清楚如何做到這一點。引用而不是價值是什麼意思? –

+6

作爲一般指導原則 - 如果函數的輸出不符合您的期望,那麼開始的好地方是如果函數的輸入是您期望的。 – Barry

回答

2

要閱讀完整的行(直到終止\ n),您需要使用例如std::getline(std::cin, UserInput);。否則,您目前正在閱讀第一個空格字符。

+0

謝謝你的直接回答。作爲剛剛開始通過在線教程學習C++編程的人,這個答案幫助我的不僅僅是一個模糊的答案,也不能解釋問題! –

+0

@ user2491647你提到的「模糊答案」實際上是試圖讓你思考_,而不是直接給你答案,這對你的下一個問題是沒用的。 –