visual c++ - strlen not counting newlines? -
i embedded lua project , came across strange (for me) behavior of strlen
, lua interpreting. trying load string, containing lua code, lual_loadbuffer
, consistently threw error of "unexpected symbol
" on whatever last line of lua code, except if whole chunk written in 1 line. example:
function start() print("start") end
would results error: unexpected symbol on 3rd line, but
function start() print("start") end
loads successfully.
i figured out loading same chunk lual_loadstring
, gives no errors, , saw uses strlen
determine length of specified string (i used std::string::size
) , using strlen provide length of string lual_loadbuffer
results in successful loading.
now question was: may difference between strlen , std::string::size, , @ surprise answer strlen not counting new lines ('\n
'). is:
const char* str = "this string\nthis newline"; std::string str2(str); str2.size(); // gives 34 strlen(str); // gives 33
the difference between size, , value returned strlen number of new line characters.
my questions are:
- does strlen not counting newlines or missing something?
- how newlines affect interpretation of lua code internally?
i using vs 2015 , lua 5.3.0
edit:
my first example not exact, , did not produce detailed effect me neither, able recreate problem original code:
std::fstream _stream("test.lua", std::ios::ate | std::ios::in); std::string _source; if(_stream.is_open()) { _source.resize(_stream.tellg()); _stream.seekg(0, std::ios::beg); _stream.read(&_source[0], _source.size()); _stream.close(); } std::cout << "std::string::size() = " << _source.size() << std::endl; std::cout << "strlen() = " << strlen(_source.c_str()) << std::endl;
the content of test.lua "function start()\n\tprint("start")\nend\n\nstart()"
the difference number of newlines:
window's line endings (cr+lf) 2 characters making file size larger number of characters in string resize
operation uses file size , not length of null-terminated string. strlen
reports length of null-terminated string , counts \n
single character. can make size match length of c string resizing string match afterwards:
_source.resize(strlen(_source.c_str()) + 1);
Comments
Post a Comment