W.K.S
W.K.S

Reputation: 10095

The code is supposed to return string without spaces, but it returns string until first space character

I'm making a console calculator, and I want to remove any whitespace that the user might enter while using the program. This is the code:

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

if i entered 2 + 2 =, output should be 2+2= but the output is: 2 am i using the wrong function here?

Upvotes: 3

Views: 780

Answers (3)

slashmais
slashmais

Reputation: 7155

I use the following function I wrote:

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

You can adapt it to your needs.

Upvotes: 0

Jon
Jon

Reputation: 437356

The problem is with getting the user input, not with stripping the spaces.

The code that removes spaces is correct, as you can see for yourself on IDEone.

The problem is that operator std::istream::operator >> stops reading input on encountering the first whitespace character. You should use another function (such as getLine) instead.

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

Your use of remove_if and erase is fine. Your method for getting input is not. operator>> is whitespace delimited. Use getline instead.

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

Upvotes: 1

Related Questions