user15183312
user15183312

Reputation: 29

Whitespace at the every first character of the string while printing it

This program takes a line, separates each word and adds them into a vector. But while printing the strings from vector after the first word all the remaining words contain a whitespace character at the beginning. I want those whitespaces to be removed.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void addmember(string s) {
    vector<string> vlist;
    string buf;
    for(int i = 0; i < s.length(); i++) {
        if(s[i] == ' ') {
            buf.push_back('\0');
            vlist.push_back(buf);
            buf.erase();
        }
        buf.push_back(s[i]);
    }
    for(auto it : vlist) {
        cout << it << "\t" << it.size() << endl;
    }
}

int main() {
    string s = "A friend is someone who knows all about you";
    addmember(s);
    return 0;
}

Output:

A
 friend
 is
 someone
 who
 knows
 all
 about

Upvotes: 1

Views: 545

Answers (2)

lopho
lopho

Reputation: 177

You push the character onto the buf string even if it is a whitespace.

Put buf.push_back(s[i]) in a else branch.

for (int i = 0; i < s.length(); i++) {
    if (s[i] == ' ') {
        vlist.push_back(buf);
        buf.erase();
    }
    else {
        buf.push_back(s[i]);
    }
}

Edit: As you use strings in the vector as well as cout << and not char*/char[] one can assume you only want C++ style strings.

If so, you should also remove the insertion of \0 terminators at the end of each substring. C++ strings are not zero terminated.

Upvotes: 2

Yksisarvinen
Yksisarvinen

Reputation: 22176

You push_back() every s[i], no matter what it is. You want to do that only if s[i] is not a space:

for(int i=0; i<s.length(); i++){
    if(s[i] == ' '){
        vlist.push_back(buf);
        buf.erase();
    } else {
        buf.push_back(s[i]);
    }
}

Upvotes: 0

Related Questions