Reputation: 604
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();
}
Upvotes: 9
Views: 30608
Reputation: 728
ifstream ifs(filename);
string str, output;
vector<string> map;
while (getline(ifs, str, ' ')) {
map.push_back(str);
}
for(int i=0; i < map.size();i++){
string dataString = map[i];
for(int j=0; j < dataString.length(); j++){
if(isspace(dataString[j])){
continue;
}
else{
output +=dataString[j];
}
}
}
Upvotes: -1
Reputation: 4144
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.
Upvotes: 1
Reputation: 67211
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());
Upvotes: 13
Reputation: 224857
The issue is that cin >> input
only reads until the first space. Use getline()
instead. (Thanks, @BenjaminLindley!)
Upvotes: 9
Reputation: 490048
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.
Upvotes: 3