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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With