Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream >> inconsistent '\n' delimiter behaviour

I have the following function to read in a stream of text and chop it up into a vector of a given type:

template<class Type>
void parse_string(std::vector<Type> &type_vector, char *string) 
{
    std::stringstream stream(string);
    while (stream.good()) 
    {
        Type t;
        stream >> t;
        type_vector.push_back(t);
    }
}

The char *string parameter is a chunk of text representing either floating point numbers or strings each separated with either ' ' or '\n'.

Now my issue is that when given a std::vector<float> type_vector, the parse_string function will separate by both the ' ' or '\n' delimiters. For example for:

0.01 0.02 0.03 0.04
0.05 0.06 0.07 0.08

it will read '0.04' and '0.05' as separate tokens. This is what I want!

However if given a std::vector<std::string> type_vector, the parse_string will only separate by ' '. Therefore if my text is as follows:

root_joint left_hip left_knee left_ankle
left_foot right_hip right_knee right_ankle

it will read 'left_ankleleft_foot' as a single token. It doesn't seem to take into account that there is a '\n' between 'left_ankle' and 'left_foot'.

What is causing this?

EDIT:

The exact char* arguments as seen in the debugger are as follows:

0.01 0.02 0.03 0.040.05 0.06 0.07 0.08

root_joint left_hip left_knee left_ankleleft_foot right_hip right_knee right_ankle

So it seems to completely ignore the '\n' from the file...

EDIT2:

Okay I figured out what I was doing wrong. As many of you pointed out, it had nothing to do with stringstream.

My parser required a std::vector copy of the file. In the process of reading the file into a string and converting it into the vector, I used the getLine(std::ifstream, std::string) function, which as you can guess, strips the '\n' newline character.

like image 202
kbirk Avatar asked Aug 10 '26 01:08

kbirk


1 Answers

You are reading the string incorrectly, so that \n is discarded. \n should lead to a split.

like image 95
Christopher Oezbek Avatar answered Aug 12 '26 17:08

Christopher Oezbek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!