Hi. I'm writing a function that should parse a string containing a description of a dice roll, for instance "2*1d8+2". I extract the four values OK when they are integers, but I want to be able to use floats as well for the multiplier and the addition at the end. Things get nasty when I try to parse such a string: "1.8*1d8+2.5".
I have determined that the problem is with the function strcspn
. I ask it to parse the input string s
(which contains the dice string) and stop at either an asterisk or an 'x':
const char * s = "1.8*1d8+2.5";
size_t l = strcspn(s,"*x");
The function should return 3
, as the asterisk is at the 4th position. However, it seems to stop on the decimal separator (period) and returns 1
.
It's not that I can't continue writing my function without this, as there are other ways to get things done, but still I'm curious why such a thing would happen. Has anyone ever encountered this problem before?
[EDIT]
Nevermind, I've found the answer, and it was my stupidity rather than the compiler playing tricks on me. I used this code:
if (l = strcspn(s,"*x") < strlen(s)) {
...
which returned 1
(or true
) because strcspn(s,"*x") < strlen(s)
evaluates to true
- and was assigned to the l
variable. I should have added parentheses:
if ((l = strcspn(s,"*x")) < strlen(s)) {
...
Thanks for your answers nonetheless, particularly @sleske, who made me analyse my code more deeply (which led to finding the answer).