The question is actually a bit vague: by "without any spaces",
do you mean "without any white space" or "without any space
characters"; the expression is widely used with both meanings.
(The space character is white space, but so it a tab, or even
a new line.)
At any rate, std::cin >> text
will never put any white space into
text
; that's how it is defined. If you want to read
a complete line, you need std::getline
. And while you're on
the right track with your loop, you don't test the character
immediately after the one you erased. This is a classic problem
when removing elements; when you remove an element, you don't
want to increment.
For the rest, of course: I'm assuming you're doing this as an
exercise: a professional would probably write:
text.erase( std::remove( text.begin(), text.end(), ' ' ), text.end() );
(or use std::remove_if
and a functional object if the goal was
to remove all white space).
And finally, if you switch to using std::isspace
: you cannot
call it directly with a char
without risking undefined
behavior. You must convert your char
to unsigned char
first.