Erase white spaces from stream

I input 9X^3 + 5X into a string using the getline() function.

I want to erase the white spaces in order to obtain 9X^3+5X.

I can do that with a simple for-loop but I came about the skipws manipulator. Can I use it here?
Last edited on
Nope. Stream manipulators work with the extraction and insertion operators. Skipws is set to on by default so you'd be already using it if you used >> or <<
So if I write
1
2
string temp;
cin >> skipws >> temp;
and I input
" C"
temp becomes
"C"
?

Whereas if I write
1
2
3
string temp;
cin >> skipws;
cin.getline(temp);
and I input the same string temp becomes
" C"
?
Last edited on
To swallow the leading whitespace before an unformatted input function such as getline(), you want to use ws, not skipws.

1
2
cin >> ws;
getline(cin, temp);


Formatted input functions, such as operator>>, do it automatically *unless* you use noskipws. Skipws just reaffirms the default settings.

I don't see how that helps you solve your original task of removing whitespace from a string. Just erase-remove:

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
    std::string s = "9X^3 + 5X";
    s.erase( std::remove(s.begin(), s.end(), ' '), s.end());
    std::cout << s << '\n';
}


or even simpler

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <boost/algorithm/string/erase.hpp>

int main()
{
    std::string s = "9X^3 + 5X";
    boost::erase_all(s, " ");
    std::cout << s << '\n';
}

demo: http://ideone.com/ek7Owy
Last edited on
Topic archived. No new replies allowed.