我已經看過這兩個問題:在C++字符串刪除空格不起作用
出於某種原因,我永遠無法得到的解決方案正常工作。在我的程序中,我收集來自用戶的輸入並將其傳遞給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
字符的解決方案,這給了我同樣的問題。
使用調試器逐步完成,你應該看到你真正的問題。 – chris
@ DOUGLASO.MOEN,我不太清楚如何做到這一點。引用而不是價值是什麼意思? –
作爲一般指導原則 - 如果函數的輸出不符合您的期望,那麼開始的好地方是如果函數的輸入是您期望的。 – Barry