Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing all spaces during tokenization

How can I remove all spaces between tokens in the following code?

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    string s[3] = {"a 1", "b    2", "c  3"};
    for (int i = 0; i < 3; i++) {
        stringstream ss(s[i]);
        string tok;
        while(getline(ss, tok, ' '))  // <-- need to fix
        {
            cout << tok << ".";  // <-- need to fix
        }
        cout << endl;
    }
    return 0;
}

The expected output is

a.1
b.2
c.3

But the code generates

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a.1.
b....2.
c..3.

>Solution :

You could use formatted input from the stream instead of std::getline. Formatted input skips whitespaces by default:

#include <iostream>
#include <sstream>

int main() {
    std::string s[3] = {"a 1", "b    2", "c  3"};

    for (const auto& str : s) {
        std::istringstream ss(str);

        if (std::string tok; ss >> tok) {
            // at least one token read, print it
            std::cout << tok;

            // then read the rest and prepend them with '.' instead:
            while (ss >> tok) {
                std::cout << '.' << tok;
            }
        }
        std::cout << '\n';
    }
}

Output:

a.1
b.2
c.3

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading