c++ - Stop carriage return from appearing in stringstream -
i'm have text parsing i'd behave identically whether read file or stringstream. such, i'm trying use std::istream
perform work. in string version, i'm trying read static memory byte array i've created (which text file). let's original file looked this:
4
the corresponding byte array this:
const char byte_array[] = { 52, 13, 10 };
where 52 ascii character 4, carriage return, linefeed.
when read directly file, parsing works fine.
when try read in "string mode" this:
std::istringstream iss(byte_array); std::istream& = iss;
i end getting carriage returns stuck on end of strings retrieve stringstream method:
std::string line; std::getline(is, line);
this screws parsing because string.empty()
method no longer gets triggered on "blank" lines -- every line contains @ least 13
carriage return if it's empty in original file generated binary data.
why ifstream
behaving differently istringstream
in respect? how can have istringstream
version discard carriage return ifstream
version does?
std::ifstream
operates in text mode default, means convert non-lf line endings single lf. in case, std::ifstream
removing cr character before std::getline()
ever sees it.
std::istringstream
not interpretation of source string, , passes through bytes in string.
it's important note std::string
represents sequence of bytes, not characters. typically 1 uses std::string
store ascii-encoded text, can used store arbitrary binary data. assumption if have read text file memory, have done text transformations such standardization of line endings.
the correct course of action here convert line endings when file being read. in case, looks generating code file. program reads file , converts code should eliminating cr characters.
an alternative approach write stream wrapper takes std::istream
, delegates read operations it, converting line endings on fly. approach viable, though can tricky right. (efficiently handling seeking, in particular, difficult.)
Comments
Post a Comment