C ++ remove spaces

I have this code to remove spaces in std :: string and it removes all characters after space. Therefore, if I have "abc def", it returns only "abc". How do I get him to switch 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(); } 
+6
source share
5 answers

The problem is that cin >> input is read only up to the first space. Use getline() instead. (Thanks, @BenjaminLindley!)

+9
source

Well, the actual problem you were talking about was mentioned by others regarding cin >> But you can use the code below to remove spaces from a string:

 str.erase(remove(str.begin(),str.end(),' '),str.end()); 
+7
source

Since the >> operator skips spaces anyway, you can do something like:

 while (std::cin>>input) std::cout << input; 

This, however, will copy the entire file (deleted space), and not just one line.

+1
source

My function to delete 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 const char x to ' ' (space, blanco) to complete the job. Hope this helps.

+1
source
 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]; } } } 
-1
source

Source: https://habr.com/ru/post/903158/


All Articles