C++ remove whitespace
Solution 1
The issue is that cin >> input
only reads until the first space. Use getline()
instead. (Thanks, @BenjaminLindley!)
Solution 2
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());
Solution 3
Since the >>
operator skips whitespace anyway, you can do something like:
while (std::cin>>input)
std::cout << input;
This, however, will copy the entire file (with whitespace removed) rather than just one line.
Solution 4
My function for removing a character is called "conv":
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
string conv(string first, char chr)
{
string ret,s="x";
for (int i=0;i<first.length();i++)
{
if (first[i]!=chr)
s=s+first[i];
}
first=s;
first.erase(0,1);
ret=first;
return ret;
}
int main()
{
string two,casper="testestestest";
const char x='t';
cout<<conv(casper,x);
system("PAUSE");
return 0;
}
You need to change the const char x
to ' '
(whitespace, blanco) for the job to be done. Hope this helps.
tr0yspradling
Updated on July 09, 2022Comments
-
tr0yspradling almost 2 years
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(); }
-
Benjamin Lindley over 12 yearsYou mean the getline free function, since it's better, and
input
is astd::string
anyway. -
BruceAdi over 12 yearsAs @BenjaminLindley mentioned, use
istream& getline ( istream& is, string& str, char delim ); istream& getline ( istream& is, string& str );
-
user2007447 over 9 yearsplease use english in your code... This is why C++ keywords are in english, to be globally understood...
-
Aleksandar over 9 years@user2007447 that was truly an onld
-
Adrian McCarthy over 6 yearsThat's for removing the spaces from the string in-place. If you want a copy without the spaces (as in the OP), you can use
std::copy_if(input.begin(), input.end(), std::back_inserter(output), [](char ch) { return ch != ' '; });
.