Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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?

like image 406
W.K.S Avatar asked Dec 06 '25 18:12

W.K.S


1 Answers

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.

like image 172
Jon Avatar answered Dec 08 '25 07:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!