Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ remove whitespace

Tags:

c++

string

std

stl

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();
}
like image 419
tr0yspradling Avatar asked Dec 06 '11 03:12

tr0yspradling


People also ask

How do I remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

What is trailing whitespace in C?

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.

How does C handle whitespace?

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.


2 Answers

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());
like image 89
Vijay Avatar answered Oct 28 '22 06:10

Vijay


The issue is that cin >> input only reads until the first space. Use getline() instead. (Thanks, @BenjaminLindley!)

like image 32
Ry- Avatar answered Oct 28 '22 06:10

Ry-