Reputation: 37
I am having issues with sscanf_s, essentially I have this line of code:
sscanf_s( line.c_str(),
"<float_array id=\"%*s[^\"]\" count=\"%*d\">%[^<]s",
numString);
I am feeding it this line of text:
<float_array id="Cube-mesh-positions-array" count="24">1 1 -1 1 -1 -1 -1 -0.9999998 -1 -0.9999997 1 -1 1 0.9999995 1 0.9999994 -1.000001 1 -1 -0.9999997 1 -1 1 1</float_array>
What I am trying to achieve is read the number array written after count="24">
and pass it to another function, however numString
remains with a value of ""
after being passed through the equation, therefore causing the subsequent functions to fail. if anyone could offer me insight into why this is occurring I would be very appreciative.
A short SSCCE that I have tested has revealed that the problem lies elsewhere, I shall have to investigate this further - sorry for wasting your time, and thank you for taking your time to try and help me.
Upvotes: 3
Views: 23142
Reputation: 40145
char numString[ 256 ];
sscanf_s( line.c_str(),
"<float_array id=\"%*[^\"]\" count=\"%*d\">%255[^<]",
numString, 256);
Upvotes: 1
Reputation: 70263
The function sscanf_s
is a Microsoft invention, intended to be "more secure" than the standard sscanf
function.
As such, if you are using "%s"
or "%c"
, it requires two parameters: One being the buffer to write the input to, and an integer specifying the available size of the buffer, so that a long input string does not result in a buffer overflow.
Unfortunately this is not quite that obvious to users of the function (like yourself), resulting in frequent mis-use of the function (which somewhat reduces the "security" implied).
Link to the Microsoft docs; refer to the section "remarks".
So what you have here is undefined behaviour, as sscanf_s
attempts to read an integer from the stack where you haven't put one. You end up lucky that the memory read is apparently zero, so zero bytes are written to numString
.
This should do nicely:
size_t BUFSIZE = 50;
char numString[ BUFSIZE ];
sscanf_s( line.c_str(),
"<float_array id=\"%*s[^\"]\" count=\"%*d\">%[^<]s",
numString, BUFSIZE );
Note that numString
better actually be a char[]
. Your question was initially tagged as C++; if numString
is actually a std::string
, be advised that you cannot use the scanf
family function with std::string
parameters.
(Sorry for the edits, got it wrong the first few times. That format string is something... ;-) )
Upvotes: 10