Reputation: 4022
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.
Upvotes: 3
Views: 823
Reputation: 26353
You are reading the string incorrectly, so that \n is discarded. \n should lead to a split.
Upvotes: 1