user11397473
user11397473

Reputation:

How to fix my code to remove the spaces in a string?

So I am trying to remove spaces from a string but if I input for example "hello world" it only return "hello" and not "helloworld". I am not sure why it does this.

string removeSpaces(string str)
{
    str.erase(remove(str.begin(), str.end(), ' '), str.end());
    return str;
}

int main()
{
    std::string input;
    std::cout << "Enter word: ";
    std::cin >> input;

    input = removeSpaces(input);
    std::cout << input;
    return 0;
}

Upvotes: 1

Views: 87

Answers (2)

Marcus Ritt
Marcus Ritt

Reputation: 477

Because std::cin >> input reads only "hello".

Upvotes: 0

bolov
bolov

Reputation: 75688

The problem is not with the function (as far as I can see). It's with the way you read the input.

std::cin >> input will read until a white space. So input will be "Hello".

To read the whole line use

std::getline(std::cin, input);

Upvotes: 6

Related Questions