Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::getline removes whitespaces?

Tags:

c++

whitespace

So I am creating a command line application and I am trying to allow commands with parameters, or if the parameter is enclosed with quotations, it will be treated as 1 parameter.

Example: test "1 2"

"test" will be the command, "1 2" will be a single parameter passed.

Using the following code snippet:

while(getline(t, param, ' ')) {
    if (param.find("\"") != string::npos) {
        ss += param;
        if (glue) {
            glue = false;
            params.push_back(ss);
            ss = "";
        }
        else {
            glue = true;
        }
    }
    else {
        params.push_back(param);
    }
}

However std::getline seems to auto remove whitespace which is causing my parameters to change from "1 2" to "12"

I've looked around but results are flooded with "How to remove whitespace" answers rather than "How to not remove whitespace"

Anybody have any suggestions?

like image 784
user1324726 Avatar asked Jan 16 '23 23:01

user1324726


2 Answers

However std::getline seems to auto remove whitespace

That's exactly what you are telling getline to do:

getline(t, param, ' ');

The third argument in getline is the delimiter. If you want to parse the input line, you should read it until '\n' is found and then process it:

while(getline(t, param)) {
    /* .. */
}
like image 180
mfontanini Avatar answered Jan 25 '23 15:01

mfontanini


Umm, you are telling it to use ' ' as a delimiter in std::getline. Of course it's going to strip the whitespace. http://www.cplusplus.com/reference/string/getline/

like image 39
Thomas Eding Avatar answered Jan 25 '23 13:01

Thomas Eding