I have this code to remove whitespace in a std::string and it removes all characters after the space. So if I have "abc def" it only returns "abc". How do I get it to go from "abc def ghi" to "abcdefghi"?
#include<iostream>
#include<algorithm>
#include<string>
int main(int argc, char* argv[]) {
std::string input, output;
std::getline(std::cin, input);
for(int i = 0; i < input.length(); i++) {
if(input[i] == ' ') {
continue;
} else {
output += input[i];
}
}
std::cout << output;
std::cin.ignore();
}
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
Trailing whitespace. Description: Used when there is whitespace between the end of a line and the newline. Problematic code: print("Hello") # [trailing-whitespace] # ^^^ trailing whitespaces.
When parsing code, the C compiler ignores white-space characters unless you use them as separators or as components of character constants or string literals. Use white-space characters to make a program more readable. Note that the compiler also treats comments as white space.
Well the actual problem you had was mentioned by others regarding the cin >>
But you can use the below code for removing the white spaces from the string:
str.erase(remove(str.begin(),str.end(),' '),str.end());
The issue is that cin >> input
only reads until the first space. Use getline()
instead. (Thanks, @BenjaminLindley!)
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