user2491647 user2491647 - 2 months ago 5x
C++ Question

Remove whitespace in C++ string doesn't work

I have read these two questions already:

  1. Remove spaces from std::string in C++

  2. remove whitespace in std::string

For some reason, I can never get the solutions to work correctly. In my program, I collect input from the user and pass it to an
. From there, I want to remove all of the spaces in it. For example, if the user inputs "3 + 2", I would like it to change to "3+2".

What happens is, whatever is before the first string is kept. Here is my program:

#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;

So when I run this program and type in "3 + 2", the output is "3".

Here is my console:

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

I cannot figure out how to resolve this. I even tried using a solution that involved using a regex to remove all the
characters, and that gave me the same issue.


To read the complete line (up to terminating \n), you need to use e.g. std::getline(std::cin, UserInput);. Otherwise, you're currently reading text up to first whitespace character.